;
(function () {
    var _excluded = ["content", "explanation", "offset"];

    function _superPropGet(t, o, e, r) {
        var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
        return 2 & r && "function" == typeof p ? function (t) {
            return p.apply(e, t);
        } : p;
    }

    function _get() {
        return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) {
            var p = _superPropBase(e, t);
            if (p) {
                var n = Object.getOwnPropertyDescriptor(p, t);
                return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value;
            }
        }, _get.apply(null, arguments);
    }

    function _superPropBase(t, o) {
        for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));) ;
        return t;
    }

    function _objectWithoutProperties(e, t) {
        if (null == e) return {};
        var o, r, i = _objectWithoutPropertiesLoose(e, t);
        if (Object.getOwnPropertySymbols) {
            var n = Object.getOwnPropertySymbols(e);
            for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
        }
        return i;
    }

    function _objectWithoutPropertiesLoose(r, e) {
        if (null == r) return {};
        var t = {};
        for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
            if (-1 !== e.indexOf(n)) continue;
            t[n] = r[n];
        }
        return t;
    }

    function _toConsumableArray(r) {
        return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
    }

    function _nonIterableSpread() {
        throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    }

    function _iterableToArray(r) {
        if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
    }

    function _arrayWithoutHoles(r) {
        if (Array.isArray(r)) return _arrayLikeToArray(r);
    }

    function _slicedToArray(r, e) {
        return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
    }

    function _nonIterableRest() {
        throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    }

    function _iterableToArrayLimit(r, l) {
        var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
        if (null != t) {
            var e, n, i, u, a = [], f = !0, o = !1;
            try {
                if (i = (t = t.call(r)).next, 0 === l) {
                    if (Object(t) !== t) return;
                    f = !1;
                } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) ;
            } catch (r) {
                o = !0, n = r;
            } finally {
                try {
                    if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
                } finally {
                    if (o) throw n;
                }
            }
            return a;
        }
    }

    function _arrayWithHoles(r) {
        if (Array.isArray(r)) return r;
    }

    function ownKeys(e, r) {
        var t = Object.keys(e);
        if (Object.getOwnPropertySymbols) {
            var o = Object.getOwnPropertySymbols(e);
            r && (o = o.filter(function (r) {
                return Object.getOwnPropertyDescriptor(e, r).enumerable;
            })), t.push.apply(t, o);
        }
        return t;
    }

    function _objectSpread(e) {
        for (var r = 1; r < arguments.length; r++) {
            var t = null != arguments[r] ? arguments[r] : {};
            r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
                _defineProperty(e, r, t[r]);
            }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
                Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
            });
        }
        return e;
    }

    function _createForOfIteratorHelper(r, e) {
        var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
        if (!t) {
            if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
                t && (r = t);
                var _n = 0, F = function F() {
                };
                return {
                    s: F, n: function n() {
                        return _n >= r.length ? {done: !0} : {done: !1, value: r[_n++]};
                    }, e: function e(r) {
                        throw r;
                    }, f: F
                };
            }
            throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
        }
        var o, a = !0, u = !1;
        return {
            s: function s() {
                t = t.call(r);
            }, n: function n() {
                var r = t.next();
                return a = r.done, r;
            }, e: function e(r) {
                u = !0, o = r;
            }, f: function f() {
                try {
                    a || null == t.return || t.return();
                } finally {
                    if (u) throw o;
                }
            }
        };
    }

    function _unsupportedIterableToArray(r, a) {
        if (r) {
            if ("string" == typeof r) return _arrayLikeToArray(r, a);
            var t = {}.toString.call(r).slice(8, -1);
            return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
        }
    }

    function _arrayLikeToArray(r, a) {
        (null == a || a > r.length) && (a = r.length);
        for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
        return n;
    }

    function _defineProperty(e, r, t) {
        return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
            value: t,
            enumerable: !0,
            configurable: !0,
            writable: !0
        }) : e[r] = t, e;
    }

    function _regeneratorRuntime() {
        "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
        _regeneratorRuntime = function _regeneratorRuntime() {
            return e;
        };
        var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) {
                t[e] = r.value;
            }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator",
            c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag";

        function define(t, e, r) {
            return Object.defineProperty(t, e, {value: r, enumerable: !0, configurable: !0, writable: !0}), t[e];
        }

        try {
            define({}, "");
        } catch (t) {
            define = function define(t, e, r) {
                return t[e] = r;
            };
        }

        function wrap(t, e, r, n) {
            var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype),
                c = new Context(n || []);
            return o(a, "_invoke", {value: makeInvokeMethod(t, r, c)}), a;
        }

        function tryCatch(t, e, r) {
            try {
                return {type: "normal", arg: t.call(e, r)};
            } catch (t) {
                return {type: "throw", arg: t};
            }
        }

        e.wrap = wrap;
        var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {};

        function Generator() {
        }

        function GeneratorFunction() {
        }

        function GeneratorFunctionPrototype() {
        }

        var p = {};
        define(p, a, function () {
            return this;
        });
        var d = Object.getPrototypeOf, v = d && d(d(values([])));
        v && v !== r && n.call(v, a) && (p = v);
        var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);

        function defineIteratorMethods(t) {
            ["next", "throw", "return"].forEach(function (e) {
                define(t, e, function (t) {
                    return this._invoke(e, t);
                });
            });
        }

        function AsyncIterator(t, e) {
            function invoke(r, o, i, a) {
                var c = tryCatch(t[r], t, o);
                if ("throw" !== c.type) {
                    var u = c.arg, h = u.value;
                    return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
                        invoke("next", t, i, a);
                    }, function (t) {
                        invoke("throw", t, i, a);
                    }) : e.resolve(h).then(function (t) {
                        u.value = t, i(u);
                    }, function (t) {
                        return invoke("throw", t, i, a);
                    });
                }
                a(c.arg);
            }

            var r;
            o(this, "_invoke", {
                value: function value(t, n) {
                    function callInvokeWithMethodAndArg() {
                        return new e(function (e, r) {
                            invoke(t, n, e, r);
                        });
                    }

                    return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
                }
            });
        }

        function makeInvokeMethod(e, r, n) {
            var o = h;
            return function (i, a) {
                if (o === f) throw Error("Generator is already running");
                if (o === s) {
                    if ("throw" === i) throw a;
                    return {value: t, done: !0};
                }
                for (n.method = i, n.arg = a; ;) {
                    var c = n.delegate;
                    if (c) {
                        var u = maybeInvokeDelegate(c, n);
                        if (u) {
                            if (u === y) continue;
                            return u;
                        }
                    }
                    if ("next" === n.method) n.sent = n._sent = n.arg; else if ("throw" === n.method) {
                        if (o === h) throw o = s, n.arg;
                        n.dispatchException(n.arg);
                    } else "return" === n.method && n.abrupt("return", n.arg);
                    o = f;
                    var p = tryCatch(e, r, n);
                    if ("normal" === p.type) {
                        if (o = n.done ? s : l, p.arg === y) continue;
                        return {value: p.arg, done: n.done};
                    }
                    "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
                }
            };
        }

        function maybeInvokeDelegate(e, r) {
            var n = r.method, o = e.iterator[n];
            if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
            var i = tryCatch(o, e.iterator, r.arg);
            if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
            var a = i.arg;
            return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
        }

        function pushTryEntry(t) {
            var e = {tryLoc: t[0]};
            1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
        }

        function resetTryEntry(t) {
            var e = t.completion || {};
            e.type = "normal", delete e.arg, t.completion = e;
        }

        function Context(t) {
            this.tryEntries = [{tryLoc: "root"}], t.forEach(pushTryEntry, this), this.reset(!0);
        }

        function values(e) {
            if (e || "" === e) {
                var r = e[a];
                if (r) return r.call(e);
                if ("function" == typeof e.next) return e;
                if (!isNaN(e.length)) {
                    var o = -1, i = function next() {
                        for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
                        return next.value = t, next.done = !0, next;
                    };
                    return i.next = i;
                }
            }
            throw new TypeError(_typeof(e) + " is not iterable");
        }

        return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
            value: GeneratorFunctionPrototype,
            configurable: !0
        }), o(GeneratorFunctionPrototype, "constructor", {
            value: GeneratorFunction,
            configurable: !0
        }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
            var e = "function" == typeof t && t.constructor;
            return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
        }, e.mark = function (t) {
            return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
        }, e.awrap = function (t) {
            return {__await: t};
        }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
            return this;
        }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
            void 0 === i && (i = Promise);
            var a = new AsyncIterator(wrap(t, r, n, o), i);
            return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
                return t.done ? t.value : a.next();
            });
        }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
            return this;
        }), define(g, "toString", function () {
            return "[object Generator]";
        }), e.keys = function (t) {
            var e = Object(t), r = [];
            for (var n in e) r.push(n);
            return r.reverse(), function next() {
                for (; r.length;) {
                    var t = r.pop();
                    if (t in e) return next.value = t, next.done = !1, next;
                }
                return next.done = !0, next;
            };
        }, e.values = values, Context.prototype = {
            constructor: Context, reset: function reset(e) {
                if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
            }, stop: function stop() {
                this.done = !0;
                var t = this.tryEntries[0].completion;
                if ("throw" === t.type) throw t.arg;
                return this.rval;
            }, dispatchException: function dispatchException(e) {
                if (this.done) throw e;
                var r = this;

                function handle(n, o) {
                    return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
                }

                for (var o = this.tryEntries.length - 1; o >= 0; --o) {
                    var i = this.tryEntries[o], a = i.completion;
                    if ("root" === i.tryLoc) return handle("end");
                    if (i.tryLoc <= this.prev) {
                        var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc");
                        if (c && u) {
                            if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
                            if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
                        } else if (c) {
                            if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
                        } else {
                            if (!u) throw Error("try statement without catch or finally");
                            if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
                        }
                    }
                }
            }, abrupt: function abrupt(t, e) {
                for (var r = this.tryEntries.length - 1; r >= 0; --r) {
                    var o = this.tryEntries[r];
                    if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
                        var i = o;
                        break;
                    }
                }
                i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
                var a = i ? i.completion : {};
                return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
            }, complete: function complete(t, e) {
                if ("throw" === t.type) throw t.arg;
                return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
            }, finish: function finish(t) {
                for (var e = this.tryEntries.length - 1; e >= 0; --e) {
                    var r = this.tryEntries[e];
                    if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
                }
            }, catch: function _catch(t) {
                for (var e = this.tryEntries.length - 1; e >= 0; --e) {
                    var r = this.tryEntries[e];
                    if (r.tryLoc === t) {
                        var n = r.completion;
                        if ("throw" === n.type) {
                            var o = n.arg;
                            resetTryEntry(r);
                        }
                        return o;
                    }
                }
                throw Error("illegal catch attempt");
            }, delegateYield: function delegateYield(e, r, n) {
                return this.delegate = {
                    iterator: values(e),
                    resultName: r,
                    nextLoc: n
                }, "next" === this.method && (this.arg = t), y;
            }
        }, e;
    }

    function _typeof(o) {
        "@babel/helpers - typeof";
        return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
            return typeof o;
        } : function (o) {
            return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
        }, _typeof(o);
    }

    function asyncGeneratorStep(n, t, e, r, o, a, c) {
        try {
            var i = n[a](c), u = i.value;
        } catch (n) {
            return void e(n);
        }
        i.done ? t(u) : Promise.resolve(u).then(r, o);
    }

    function _asyncToGenerator(n) {
        return function () {
            var t = this, e = arguments;
            return new Promise(function (r, o) {
                var a = n.apply(t, e);

                function _next(n) {
                    asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
                }

                function _throw(n) {
                    asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
                }

                _next(void 0);
            });
        };
    }

    function _defineProperties(e, r) {
        for (var t = 0; t < r.length; t++) {
            var o = r[t];
            o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
        }
    }

    function _createClass(e, r, t) {
        return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {writable: !1}), e;
    }

    function _toPropertyKey(t) {
        var i = _toPrimitive(t, "string");
        return "symbol" == _typeof(i) ? i : i + "";
    }

    function _toPrimitive(t, r) {
        if ("object" != _typeof(t) || !t) return t;
        var e = t[Symbol.toPrimitive];
        if (void 0 !== e) {
            var i = e.call(t, r || "default");
            if ("object" != _typeof(i)) return i;
            throw new TypeError("@@toPrimitive must return a primitive value.");
        }
        return ("string" === r ? String : Number)(t);
    }

    function _classCallCheck(a, n) {
        if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
    }

    function _callSuper(t, o, e) {
        return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
    }

    function _possibleConstructorReturn(t, e) {
        if (e && ("object" == _typeof(e) || "function" == typeof e)) return e;
        if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
        return _assertThisInitialized(t);
    }

    function _assertThisInitialized(e) {
        if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
        return e;
    }

    function _inherits(t, e) {
        if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
        t.prototype = Object.create(e && e.prototype, {
            constructor: {
                value: t,
                writable: !0,
                configurable: !0
            }
        }), Object.defineProperty(t, "prototype", {writable: !1}), e && _setPrototypeOf(t, e);
    }

    function _wrapNativeSuper(t) {
        var r = "function" == typeof Map ? new Map() : void 0;
        return _wrapNativeSuper = function _wrapNativeSuper(t) {
            if (null === t || !_isNativeFunction(t)) return t;
            if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
            if (void 0 !== r) {
                if (r.has(t)) return r.get(t);
                r.set(t, Wrapper);
            }

            function Wrapper() {
                return _construct(t, arguments, _getPrototypeOf(this).constructor);
            }

            return Wrapper.prototype = Object.create(t.prototype, {
                constructor: {
                    value: Wrapper,
                    enumerable: !1,
                    writable: !0,
                    configurable: !0
                }
            }), _setPrototypeOf(Wrapper, t);
        }, _wrapNativeSuper(t);
    }

    function _construct(t, e, r) {
        if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
        var o = [null];
        o.push.apply(o, e);
        var p = new (t.bind.apply(t, o))();
        return r && _setPrototypeOf(p, r.prototype), p;
    }

    function _isNativeReflectConstruct() {
        try {
            var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {
            }));
        } catch (t) {
        }
        return (_isNativeReflectConstruct = function _isNativeReflectConstruct() {
            return !!t;
        })();
    }

    function _isNativeFunction(t) {
        try {
            return -1 !== Function.toString.call(t).indexOf("[native code]");
        } catch (n) {
            return "function" == typeof t;
        }
    }

    function _setPrototypeOf(t, e) {
        return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
            return t.__proto__ = e, t;
        }, _setPrototypeOf(t, e);
    }

    function _getPrototypeOf(t) {
        return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
            return t.__proto__ || Object.getPrototypeOf(t);
        }, _getPrototypeOf(t);
    }

    System.register(['./index-legacy-BBSVeb5I.js'], function (exports, module) {
        'use strict';

        var shallowRef, ref, __vitePreload, defineComponent, watchEffect, createElementBlock, unref, openBlock,
            useTimeoutFn;
        return {
            setters: [function (module) {
                shallowRef = module.T;
                ref = module.e;
                __vitePreload = module.a8;
                defineComponent = module.d;
                watchEffect = module.U;
                createElementBlock = module.a;
                unref = module.u;
                openBlock = module.o;
                useTimeoutFn = module.a9;
            }],
            execute: function execute() {
                var _BasicScopeAttributesProvider2, _StateStackImpl2;
                exports("u", useCopy);

                function escapeHtml(value) {
                    return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;");
                }

                var ShikiError$2 = /*#__PURE__*/function (_Error) {
                    function ShikiError(message) {
                        var _this;
                        _classCallCheck(this, ShikiError);
                        _this = _callSuper(this, ShikiError, [message]);
                        _this.name = "ShikiError";
                        return _this;
                    }

                    _inherits(ShikiError, _Error);
                    return _createClass(ShikiError);
                }(/*#__PURE__*/_wrapNativeSuper(Error));
                var ShikiError$1 = /*#__PURE__*/function (_Error2) {
                    function ShikiError(message) {
                        var _this2;
                        _classCallCheck(this, ShikiError);
                        _this2 = _callSuper(this, ShikiError, [message]);
                        _this2.name = "ShikiError";
                        return _this2;
                    }

                    _inherits(ShikiError, _Error2);
                    return _createClass(ShikiError);
                }(/*#__PURE__*/_wrapNativeSuper(Error));

                function getHeapMax() {
                    return 2147483648;
                }

                function _emscripten_get_now() {
                    return typeof performance !== "undefined" ? performance.now() : Date.now();
                }

                var alignUp = function alignUp(x, multiple) {
                    return x + (multiple - x % multiple) % multiple;
                };

                function main(_x) {
                    return _main.apply(this, arguments);
                }

                function _main() {
                    _main = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(init) {
                        var wasmMemory, buffer, binding, updateGlobalBufferAndViews, _emscripten_memcpy_big,
                            emscripten_realloc_buffer, _emscripten_resize_heap, UTF8Decoder, UTF8ArrayToString,
                            UTF8ToString, asmLibraryArg, createWasm, _createWasm;
                        return _regeneratorRuntime().wrap(function _callee8$(_context8) {
                            while (1) switch (_context8.prev = _context8.next) {
                                case 0:
                                    _createWasm = function _createWasm3() {
                                        _createWasm = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
                                            var info, exports;
                                            return _regeneratorRuntime().wrap(function _callee7$(_context7) {
                                                while (1) switch (_context7.prev = _context7.next) {
                                                    case 0:
                                                        info = {
                                                            env: asmLibraryArg,
                                                            wasi_snapshot_preview1: asmLibraryArg
                                                        };
                                                        _context7.next = 3;
                                                        return init(info);
                                                    case 3:
                                                        exports = _context7.sent;
                                                        wasmMemory = exports.memory;
                                                        updateGlobalBufferAndViews(wasmMemory.buffer);
                                                        Object.assign(binding, exports);
                                                        binding.UTF8ToString = UTF8ToString;
                                                    case 8:
                                                    case "end":
                                                        return _context7.stop();
                                                }
                                            }, _callee7);
                                        }));
                                        return _createWasm.apply(this, arguments);
                                    };
                                    createWasm = function _createWasm2() {
                                        return _createWasm.apply(this, arguments);
                                    };
                                    UTF8ToString = function _UTF8ToString(ptr, maxBytesToRead) {
                                        return ptr ? UTF8ArrayToString(binding.HEAPU8, ptr, maxBytesToRead) : "";
                                    };
                                    UTF8ArrayToString = function _UTF8ArrayToString(heapOrArray, idx) {
                                        var maxBytesToRead = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1024;
                                        var endIdx = idx + maxBytesToRead;
                                        var endPtr = idx;
                                        while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
                                        if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
                                            return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
                                        }
                                        var str = "";
                                        while (idx < endPtr) {
                                            var u0 = heapOrArray[idx++];
                                            if (!(u0 & 128)) {
                                                str += String.fromCharCode(u0);
                                                continue;
                                            }
                                            var u1 = heapOrArray[idx++] & 63;
                                            if ((u0 & 224) === 192) {
                                                str += String.fromCharCode((u0 & 31) << 6 | u1);
                                                continue;
                                            }
                                            var u2 = heapOrArray[idx++] & 63;
                                            if ((u0 & 240) === 224) {
                                                u0 = (u0 & 15) << 12 | u1 << 6 | u2;
                                            } else {
                                                u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63;
                                            }
                                            if (u0 < 65536) {
                                                str += String.fromCharCode(u0);
                                            } else {
                                                var ch = u0 - 65536;
                                                str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
                                            }
                                        }
                                        return str;
                                    };
                                    _emscripten_resize_heap = function _emscripten_resize_he(requestedSize) {
                                        var oldSize = binding.HEAPU8.length;
                                        requestedSize = requestedSize >>> 0;
                                        var maxHeapSize = getHeapMax();
                                        if (requestedSize > maxHeapSize) return false;
                                        for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
                                            var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
                                            overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
                                            var newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536));
                                            var replacement = emscripten_realloc_buffer(newSize);
                                            if (replacement) return true;
                                        }
                                        return false;
                                    };
                                    emscripten_realloc_buffer = function _emscripten_realloc_b(size) {
                                        try {
                                            wasmMemory.grow(size - buffer.byteLength + 65535 >>> 16);
                                            updateGlobalBufferAndViews(wasmMemory.buffer);
                                            return 1;
                                        } catch (_unused) {
                                        }
                                    };
                                    _emscripten_memcpy_big = function _emscripten_memcpy_bi(dest, src, num) {
                                        binding.HEAPU8.copyWithin(dest, src, src + num);
                                    };
                                    updateGlobalBufferAndViews = function _updateGlobalBufferAn(buf) {
                                        buffer = buf;
                                        binding.HEAPU8 = new Uint8Array(buf);
                                        binding.HEAPU32 = new Uint32Array(buf);
                                    };
                                    binding = {};
                                    UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder("utf8") : undefined;
                                    asmLibraryArg = {
                                        emscripten_get_now: _emscripten_get_now,
                                        emscripten_memcpy_big: _emscripten_memcpy_big,
                                        emscripten_resize_heap: _emscripten_resize_heap,
                                        fd_write: function fd_write() {
                                            return 0;
                                        }
                                    };
                                    _context8.next = 13;
                                    return createWasm();
                                case 13:
                                    return _context8.abrupt("return", binding);
                                case 14:
                                case "end":
                                    return _context8.stop();
                            }
                        }, _callee8);
                    }));
                    return _main.apply(this, arguments);
                }

                var __defProp = Object.defineProperty;
                var __defNormalProp = function __defNormalProp(obj, key, value) {
                    return key in obj ? __defProp(obj, key, {
                        enumerable: true,
                        configurable: true,
                        writable: true,
                        value: value
                    }) : obj[key] = value;
                };
                var __publicField = function __publicField(obj, key, value) {
                    __defNormalProp(obj, _typeof(key) !== "symbol" ? key + "" : key, value);
                    return value;
                };
                var onigBinding = null;

                function throwLastOnigError(onigBinding2) {
                    throw new ShikiError$1(onigBinding2.UTF8ToString(onigBinding2.getLastOnigError()));
                }

                var UtfString = /*#__PURE__*/function () {
                    function UtfString(str) {
                        _classCallCheck(this, UtfString);
                        __publicField(this, "utf16Length");
                        __publicField(this, "utf8Length");
                        __publicField(this, "utf16Value");
                        __publicField(this, "utf8Value");
                        __publicField(this, "utf16OffsetToUtf8");
                        __publicField(this, "utf8OffsetToUtf16");
                        var utf16Length = str.length;
                        var utf8Length = UtfString._utf8ByteLength(str);
                        var computeIndicesMapping = utf8Length !== utf16Length;
                        var utf16OffsetToUtf8 = computeIndicesMapping ? new Uint32Array(utf16Length + 1) : null;
                        if (computeIndicesMapping) utf16OffsetToUtf8[utf16Length] = utf8Length;
                        var utf8OffsetToUtf16 = computeIndicesMapping ? new Uint32Array(utf8Length + 1) : null;
                        if (computeIndicesMapping) utf8OffsetToUtf16[utf8Length] = utf16Length;
                        var utf8Value = new Uint8Array(utf8Length);
                        var i8 = 0;
                        for (var i16 = 0; i16 < utf16Length; i16++) {
                            var charCode = str.charCodeAt(i16);
                            var codePoint = charCode;
                            var wasSurrogatePair = false;
                            if (charCode >= 55296 && charCode <= 56319) {
                                if (i16 + 1 < utf16Length) {
                                    var nextCharCode = str.charCodeAt(i16 + 1);
                                    if (nextCharCode >= 56320 && nextCharCode <= 57343) {
                                        codePoint = (charCode - 55296 << 10) + 65536 | nextCharCode - 56320;
                                        wasSurrogatePair = true;
                                    }
                                }
                            }
                            if (computeIndicesMapping) {
                                utf16OffsetToUtf8[i16] = i8;
                                if (wasSurrogatePair) utf16OffsetToUtf8[i16 + 1] = i8;
                                if (codePoint <= 127) {
                                    utf8OffsetToUtf16[i8 + 0] = i16;
                                } else if (codePoint <= 2047) {
                                    utf8OffsetToUtf16[i8 + 0] = i16;
                                    utf8OffsetToUtf16[i8 + 1] = i16;
                                } else if (codePoint <= 65535) {
                                    utf8OffsetToUtf16[i8 + 0] = i16;
                                    utf8OffsetToUtf16[i8 + 1] = i16;
                                    utf8OffsetToUtf16[i8 + 2] = i16;
                                } else {
                                    utf8OffsetToUtf16[i8 + 0] = i16;
                                    utf8OffsetToUtf16[i8 + 1] = i16;
                                    utf8OffsetToUtf16[i8 + 2] = i16;
                                    utf8OffsetToUtf16[i8 + 3] = i16;
                                }
                            }
                            if (codePoint <= 127) {
                                utf8Value[i8++] = codePoint;
                            } else if (codePoint <= 2047) {
                                utf8Value[i8++] = 192 | (codePoint & 1984) >>> 6;
                                utf8Value[i8++] = 128 | (codePoint & 63) >>> 0;
                            } else if (codePoint <= 65535) {
                                utf8Value[i8++] = 224 | (codePoint & 61440) >>> 12;
                                utf8Value[i8++] = 128 | (codePoint & 4032) >>> 6;
                                utf8Value[i8++] = 128 | (codePoint & 63) >>> 0;
                            } else {
                                utf8Value[i8++] = 240 | (codePoint & 1835008) >>> 18;
                                utf8Value[i8++] = 128 | (codePoint & 258048) >>> 12;
                                utf8Value[i8++] = 128 | (codePoint & 4032) >>> 6;
                                utf8Value[i8++] = 128 | (codePoint & 63) >>> 0;
                            }
                            if (wasSurrogatePair) i16++;
                        }
                        this.utf16Length = utf16Length;
                        this.utf8Length = utf8Length;
                        this.utf16Value = str;
                        this.utf8Value = utf8Value;
                        this.utf16OffsetToUtf8 = utf16OffsetToUtf8;
                        this.utf8OffsetToUtf16 = utf8OffsetToUtf16;
                    }

                    return _createClass(UtfString, [{
                        key: "createString",
                        value: function createString(onigBinding2) {
                            var result = onigBinding2.omalloc(this.utf8Length);
                            onigBinding2.HEAPU8.set(this.utf8Value, result);
                            return result;
                        }
                    }], [{
                        key: "_utf8ByteLength",
                        value: function _utf8ByteLength(str) {
                            var result = 0;
                            for (var i = 0, len = str.length; i < len; i++) {
                                var charCode = str.charCodeAt(i);
                                var codepoint = charCode;
                                var wasSurrogatePair = false;
                                if (charCode >= 55296 && charCode <= 56319) {
                                    if (i + 1 < len) {
                                        var nextCharCode = str.charCodeAt(i + 1);
                                        if (nextCharCode >= 56320 && nextCharCode <= 57343) {
                                            codepoint = (charCode - 55296 << 10) + 65536 | nextCharCode - 56320;
                                            wasSurrogatePair = true;
                                        }
                                    }
                                }
                                if (codepoint <= 127) result += 1; else if (codepoint <= 2047) result += 2; else if (codepoint <= 65535) result += 3; else result += 4;
                                if (wasSurrogatePair) i++;
                            }
                            return result;
                        }
                    }]);
                }();
                var _OnigString2 = /*#__PURE__*/function () {
                    function _OnigString(str) {
                        _classCallCheck(this, _OnigString);
                        __publicField(this, "id", ++_OnigString2.LAST_ID);
                        __publicField(this, "_onigBinding");
                        __publicField(this, "content");
                        __publicField(this, "utf16Length");
                        __publicField(this, "utf8Length");
                        __publicField(this, "utf16OffsetToUtf8");
                        __publicField(this, "utf8OffsetToUtf16");
                        __publicField(this, "ptr");
                        if (!onigBinding) throw new ShikiError$1("Must invoke loadWasm first.");
                        this._onigBinding = onigBinding;
                        this.content = str;
                        var utfString = new UtfString(str);
                        this.utf16Length = utfString.utf16Length;
                        this.utf8Length = utfString.utf8Length;
                        this.utf16OffsetToUtf8 = utfString.utf16OffsetToUtf8;
                        this.utf8OffsetToUtf16 = utfString.utf8OffsetToUtf16;
                        if (this.utf8Length < 1e4 && !_OnigString2._sharedPtrInUse) {
                            if (!_OnigString2._sharedPtr) _OnigString2._sharedPtr = onigBinding.omalloc(1e4);
                            _OnigString2._sharedPtrInUse = true;
                            onigBinding.HEAPU8.set(utfString.utf8Value, _OnigString2._sharedPtr);
                            this.ptr = _OnigString2._sharedPtr;
                        } else {
                            this.ptr = utfString.createString(onigBinding);
                        }
                    }

                    return _createClass(_OnigString, [{
                        key: "convertUtf8OffsetToUtf16",
                        value: function convertUtf8OffsetToUtf16(utf8Offset) {
                            if (this.utf8OffsetToUtf16) {
                                if (utf8Offset < 0) return 0;
                                if (utf8Offset > this.utf8Length) return this.utf16Length;
                                return this.utf8OffsetToUtf16[utf8Offset];
                            }
                            return utf8Offset;
                        }
                    }, {
                        key: "convertUtf16OffsetToUtf8",
                        value: function convertUtf16OffsetToUtf8(utf16Offset) {
                            if (this.utf16OffsetToUtf8) {
                                if (utf16Offset < 0) return 0;
                                if (utf16Offset > this.utf16Length) return this.utf8Length;
                                return this.utf16OffsetToUtf8[utf16Offset];
                            }
                            return utf16Offset;
                        }
                    }, {
                        key: "dispose",
                        value: function dispose() {
                            if (this.ptr === _OnigString2._sharedPtr) _OnigString2._sharedPtrInUse = false; else this._onigBinding.ofree(this.ptr);
                        }
                    }]);
                }();
                var OnigString = _OnigString2;
                __publicField(OnigString, "LAST_ID", 0);
                __publicField(OnigString, "_sharedPtr", 0);
                // a pointer to a string of 10000 bytes
                __publicField(OnigString, "_sharedPtrInUse", false);
                var OnigScanner = /*#__PURE__*/function () {
                    function OnigScanner(patterns) {
                        _classCallCheck(this, OnigScanner);
                        __publicField(this, "_onigBinding");
                        __publicField(this, "_ptr");
                        if (!onigBinding) throw new ShikiError$1("Must invoke loadWasm first.");
                        var strPtrsArr = [];
                        var strLenArr = [];
                        for (var i = 0, len = patterns.length; i < len; i++) {
                            var utfString = new UtfString(patterns[i]);
                            strPtrsArr[i] = utfString.createString(onigBinding);
                            strLenArr[i] = utfString.utf8Length;
                        }
                        var strPtrsPtr = onigBinding.omalloc(4 * patterns.length);
                        onigBinding.HEAPU32.set(strPtrsArr, strPtrsPtr / 4);
                        var strLenPtr = onigBinding.omalloc(4 * patterns.length);
                        onigBinding.HEAPU32.set(strLenArr, strLenPtr / 4);
                        var scannerPtr = onigBinding.createOnigScanner(strPtrsPtr, strLenPtr, patterns.length);
                        for (var _i = 0, _len = patterns.length; _i < _len; _i++) onigBinding.ofree(strPtrsArr[_i]);
                        onigBinding.ofree(strLenPtr);
                        onigBinding.ofree(strPtrsPtr);
                        if (scannerPtr === 0) throwLastOnigError(onigBinding);
                        this._onigBinding = onigBinding;
                        this._ptr = scannerPtr;
                    }

                    return _createClass(OnigScanner, [{
                        key: "dispose",
                        value: function dispose() {
                            this._onigBinding.freeOnigScanner(this._ptr);
                        }
                    }, {
                        key: "findNextMatchSync",
                        value: function findNextMatchSync(string, startPosition, arg) {
                            var options = 0 /* None */;
                            if (typeof arg === "number") {
                                options = arg;
                            }
                            if (typeof string === "string") {
                                string = new OnigString(string);
                                var result = this._findNextMatchSync(string, startPosition, false, options);
                                string.dispose();
                                return result;
                            }
                            return this._findNextMatchSync(string, startPosition, false, options);
                        }
                    }, {
                        key: "_findNextMatchSync",
                        value: function _findNextMatchSync(string, startPosition, debugCall, options) {
                            var onigBinding2 = this._onigBinding;
                            var resultPtr = onigBinding2.findNextOnigScannerMatch(this._ptr, string.id, string.ptr, string.utf8Length, string.convertUtf16OffsetToUtf8(startPosition), options);
                            if (resultPtr === 0) {
                                return null;
                            }
                            var HEAPU32 = onigBinding2.HEAPU32;
                            var offset = resultPtr / 4;
                            var index = HEAPU32[offset++];
                            var count = HEAPU32[offset++];
                            var captureIndices = [];
                            for (var i = 0; i < count; i++) {
                                var beg = string.convertUtf8OffsetToUtf16(HEAPU32[offset++]);
                                var end = string.convertUtf8OffsetToUtf16(HEAPU32[offset++]);
                                captureIndices[i] = {
                                    start: beg,
                                    end: end,
                                    length: end - beg
                                };
                            }
                            return {
                                index: index,
                                captureIndices: captureIndices
                            };
                        }
                    }]);
                }();

                function isInstantiatorOptionsObject(dataOrOptions) {
                    return typeof dataOrOptions.instantiator === "function";
                }

                function isInstantiatorModule(dataOrOptions) {
                    return typeof dataOrOptions.default === "function";
                }

                function isDataOptionsObject(dataOrOptions) {
                    return typeof dataOrOptions.data !== "undefined";
                }

                function isResponse(dataOrOptions) {
                    return typeof Response !== "undefined" && dataOrOptions instanceof Response;
                }

                function isArrayBuffer(data) {
                    var _Buffer$isBuffer, _Buffer;
                    return typeof ArrayBuffer !== "undefined" && (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) || typeof Buffer !== "undefined" && ((_Buffer$isBuffer = (_Buffer = Buffer).isBuffer) === null || _Buffer$isBuffer === void 0 ? void 0 : _Buffer$isBuffer.call(_Buffer, data)) || typeof SharedArrayBuffer !== "undefined" && data instanceof SharedArrayBuffer || typeof Uint32Array !== "undefined" && data instanceof Uint32Array;
                }

                var initPromise;

                function loadWasm(options) {
                    if (initPromise) return initPromise;

                    function _load() {
                        return _load2.apply(this, arguments);
                    }

                    function _load2() {
                        _load2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
                            return _regeneratorRuntime().wrap(function _callee2$(_context2) {
                                while (1) switch (_context2.prev = _context2.next) {
                                    case 0:
                                        _context2.next = 2;
                                        return main(/*#__PURE__*/function () {
                                            var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(info) {
                                                var instance;
                                                return _regeneratorRuntime().wrap(function _callee$(_context) {
                                                    while (1) switch (_context.prev = _context.next) {
                                                        case 0:
                                                            instance = options;
                                                            _context.next = 3;
                                                            return instance;
                                                        case 3:
                                                            instance = _context.sent;
                                                            if (!(typeof instance === "function")) {
                                                                _context.next = 8;
                                                                break;
                                                            }
                                                            _context.next = 7;
                                                            return instance(info);
                                                        case 7:
                                                            instance = _context.sent;
                                                        case 8:
                                                            if (!(typeof instance === "function")) {
                                                                _context.next = 12;
                                                                break;
                                                            }
                                                            _context.next = 11;
                                                            return instance(info);
                                                        case 11:
                                                            instance = _context.sent;
                                                        case 12:
                                                            if (!isInstantiatorOptionsObject(instance)) {
                                                                _context.next = 18;
                                                                break;
                                                            }
                                                            _context.next = 15;
                                                            return instance.instantiator(info);
                                                        case 15:
                                                            instance = _context.sent;
                                                            _context.next = 53;
                                                            break;
                                                        case 18:
                                                            if (!isInstantiatorModule(instance)) {
                                                                _context.next = 24;
                                                                break;
                                                            }
                                                            _context.next = 21;
                                                            return instance.default(info);
                                                        case 21:
                                                            instance = _context.sent;
                                                            _context.next = 53;
                                                            break;
                                                        case 24:
                                                            if (isDataOptionsObject(instance)) instance = instance.data;
                                                            if (!isResponse(instance)) {
                                                                _context.next = 37;
                                                                break;
                                                            }
                                                            if (!(typeof WebAssembly.instantiateStreaming === "function")) {
                                                                _context.next = 32;
                                                                break;
                                                            }
                                                            _context.next = 29;
                                                            return _makeResponseStreamingLoader(instance)(info);
                                                        case 29:
                                                            instance = _context.sent;
                                                            _context.next = 35;
                                                            break;
                                                        case 32:
                                                            _context.next = 34;
                                                            return _makeResponseNonStreamingLoader(instance)(info);
                                                        case 34:
                                                            instance = _context.sent;
                                                        case 35:
                                                            _context.next = 53;
                                                            break;
                                                        case 37:
                                                            if (!isArrayBuffer(instance)) {
                                                                _context.next = 43;
                                                                break;
                                                            }
                                                            _context.next = 40;
                                                            return _makeArrayBufferLoader(instance)(info);
                                                        case 40:
                                                            instance = _context.sent;
                                                            _context.next = 53;
                                                            break;
                                                        case 43:
                                                            if (!(instance instanceof WebAssembly.Module)) {
                                                                _context.next = 49;
                                                                break;
                                                            }
                                                            _context.next = 46;
                                                            return _makeArrayBufferLoader(instance)(info);
                                                        case 46:
                                                            instance = _context.sent;
                                                            _context.next = 53;
                                                            break;
                                                        case 49:
                                                            if (!("default" in instance && instance.default instanceof WebAssembly.Module)) {
                                                                _context.next = 53;
                                                                break;
                                                            }
                                                            _context.next = 52;
                                                            return _makeArrayBufferLoader(instance.default)(info);
                                                        case 52:
                                                            instance = _context.sent;
                                                        case 53:
                                                            if ("instance" in instance) instance = instance.instance;
                                                            if ("exports" in instance) instance = instance.exports;
                                                            return _context.abrupt("return", instance);
                                                        case 56:
                                                        case "end":
                                                            return _context.stop();
                                                    }
                                                }, _callee);
                                            }));
                                            return function (_x2) {
                                                return _ref.apply(this, arguments);
                                            };
                                        }());
                                    case 2:
                                        onigBinding = _context2.sent;
                                    case 3:
                                    case "end":
                                        return _context2.stop();
                                }
                            }, _callee2);
                        }));
                        return _load2.apply(this, arguments);
                    }

                    initPromise = _load();
                    return initPromise;
                }

                function _makeArrayBufferLoader(data) {
                    return function (importObject) {
                        return WebAssembly.instantiate(data, importObject);
                    };
                }

                function _makeResponseStreamingLoader(data) {
                    return function (importObject) {
                        return WebAssembly.instantiateStreaming(data, importObject);
                    };
                }

                function _makeResponseNonStreamingLoader(data) {
                    return /*#__PURE__*/function () {
                        var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(importObject) {
                            var arrayBuffer;
                            return _regeneratorRuntime().wrap(function _callee3$(_context3) {
                                while (1) switch (_context3.prev = _context3.next) {
                                    case 0:
                                        _context3.next = 2;
                                        return data.arrayBuffer();
                                    case 2:
                                        arrayBuffer = _context3.sent;
                                        return _context3.abrupt("return", WebAssembly.instantiate(arrayBuffer, importObject));
                                    case 4:
                                    case "end":
                                        return _context3.stop();
                                }
                            }, _callee3);
                        }));
                        return function (_x3) {
                            return _ref2.apply(this, arguments);
                        };
                    }();
                }

                var _defaultWasmLoader;

                function getDefaultWasmLoader() {
                    return _defaultWasmLoader;
                }

                function createOnigurumaEngine(_x4) {
                    return _createOnigurumaEngine.apply(this, arguments);
                }

                function _createOnigurumaEngine() {
                    _createOnigurumaEngine = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(options) {
                        return _regeneratorRuntime().wrap(function _callee9$(_context9) {
                            while (1) switch (_context9.prev = _context9.next) {
                                case 0:
                                    if (!options) {
                                        _context9.next = 3;
                                        break;
                                    }
                                    _context9.next = 3;
                                    return loadWasm(options);
                                case 3:
                                    return _context9.abrupt("return", {
                                        createScanner: function createScanner(patterns) {
                                            return new OnigScanner(patterns.map(function (p) {
                                                return typeof p === "string" ? p : p.source;
                                            }));
                                        },
                                        createString: function createString(s) {
                                            return new OnigString(s);
                                        }
                                    });
                                case 4:
                                case "end":
                                    return _context9.stop();
                            }
                        }, _callee9);
                    }));
                    return _createOnigurumaEngine.apply(this, arguments);
                }

                var _emitDeprecation = 3;

                function warnDeprecated(message) {
                    var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;
                    if (version > _emitDeprecation) return;
                    {
                        console.trace("[SHIKI DEPRECATE]: ".concat(message));
                    }
                }

                function clone(something) {
                    return doClone(something);
                }

                function doClone(something) {
                    if (Array.isArray(something)) {
                        return cloneArray(something);
                    }
                    if (something instanceof RegExp) {
                        return something;
                    }
                    if (_typeof(something) === "object") {
                        return cloneObj(something);
                    }
                    return something;
                }

                function cloneArray(arr) {
                    var r = [];
                    for (var i = 0, len = arr.length; i < len; i++) {
                        r[i] = doClone(arr[i]);
                    }
                    return r;
                }

                function cloneObj(obj) {
                    var r = {};
                    for (var _key in obj) {
                        r[_key] = doClone(obj[_key]);
                    }
                    return r;
                }

                function mergeObjects(target) {
                    for (var _len2 = arguments.length, sources = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
                        sources[_key2 - 1] = arguments[_key2];
                    }
                    sources.forEach(function (source) {
                        for (var _key3 in source) {
                            target[_key3] = source[_key3];
                        }
                    });
                    return target;
                }

                function basename(path) {
                    var idx = ~path.lastIndexOf("/") || ~path.lastIndexOf("\\");
                    if (idx === 0) {
                        return path;
                    } else if (~idx === path.length - 1) {
                        return basename(path.substring(0, path.length - 1));
                    } else {
                        return path.substr(~idx + 1);
                    }
                }

                var CAPTURING_REGEX_SOURCE = /\$(\d+)|\${(\d+):\/(downcase|upcase)}/g;
                var RegexSource = /*#__PURE__*/function () {
                    function RegexSource() {
                        _classCallCheck(this, RegexSource);
                    }

                    return _createClass(RegexSource, null, [{
                        key: "hasCaptures",
                        value: function hasCaptures(regexSource) {
                            if (regexSource === null) {
                                return false;
                            }
                            CAPTURING_REGEX_SOURCE.lastIndex = 0;
                            return CAPTURING_REGEX_SOURCE.test(regexSource);
                        }
                    }, {
                        key: "replaceCaptures",
                        value: function replaceCaptures(regexSource, captureSource, captureIndices) {
                            return regexSource.replace(CAPTURING_REGEX_SOURCE, function (match, index, commandIndex, command) {
                                var capture = captureIndices[parseInt(index || commandIndex, 10)];
                                if (capture) {
                                    var result = captureSource.substring(capture.start, capture.end);
                                    while (result[0] === ".") {
                                        result = result.substring(1);
                                    }
                                    switch (command) {
                                        case "downcase":
                                            return result.toLowerCase();
                                        case "upcase":
                                            return result.toUpperCase();
                                        default:
                                            return result;
                                    }
                                } else {
                                    return match;
                                }
                            });
                        }
                    }]);
                }();

                function strcmp(a, b) {
                    if (a < b) {
                        return -1;
                    }
                    if (a > b) {
                        return 1;
                    }
                    return 0;
                }

                function strArrCmp(a, b) {
                    if (a === null && b === null) {
                        return 0;
                    }
                    if (!a) {
                        return -1;
                    }
                    if (!b) {
                        return 1;
                    }
                    var len1 = a.length;
                    var len2 = b.length;
                    if (len1 === len2) {
                        for (var i = 0; i < len1; i++) {
                            var res = strcmp(a[i], b[i]);
                            if (res !== 0) {
                                return res;
                            }
                        }
                        return 0;
                    }
                    return len1 - len2;
                }

                function isValidHexColor(hex) {
                    if (/^#[0-9a-f]{6}$/i.test(hex)) {
                        return true;
                    }
                    if (/^#[0-9a-f]{8}$/i.test(hex)) {
                        return true;
                    }
                    if (/^#[0-9a-f]{3}$/i.test(hex)) {
                        return true;
                    }
                    if (/^#[0-9a-f]{4}$/i.test(hex)) {
                        return true;
                    }
                    return false;
                }

                function escapeRegExpCharacters(value) {
                    return value.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, "\\$&");
                }

                var CachedFn = /*#__PURE__*/function () {
                    function CachedFn(fn) {
                        _classCallCheck(this, CachedFn);
                        _defineProperty(this, "cache", /* @__PURE__ */new Map());
                        this.fn = fn;
                    }

                    return _createClass(CachedFn, [{
                        key: "get",
                        value: function get(key) {
                            if (this.cache.has(key)) {
                                return this.cache.get(key);
                            }
                            var value = this.fn(key);
                            this.cache.set(key, value);
                            return value;
                        }
                    }]);
                }();
                var Theme = /*#__PURE__*/function () {
                    function Theme(_colorMap, _defaults, _root) {
                        var _this3 = this;
                        _classCallCheck(this, Theme);
                        _defineProperty(this, "_cachedMatchRoot", new CachedFn(function (scopeName) {
                            return _this3._root.match(scopeName);
                        }));
                        this._colorMap = _colorMap;
                        this._defaults = _defaults;
                        this._root = _root;
                    }

                    return _createClass(Theme, [{
                        key: "getColorMap",
                        value: function getColorMap() {
                            return this._colorMap.getColorMap();
                        }
                    }, {
                        key: "getDefaults",
                        value: function getDefaults() {
                            return this._defaults;
                        }
                    }, {
                        key: "match",
                        value: function match(scopePath) {
                            if (scopePath === null) {
                                return this._defaults;
                            }
                            var scopeName = scopePath.scopeName;
                            var matchingTrieElements = this._cachedMatchRoot.get(scopeName);
                            var effectiveRule = matchingTrieElements.find(function (v) {
                                return _scopePathMatchesParentScopes(scopePath.parent, v.parentScopes);
                            });
                            if (!effectiveRule) {
                                return null;
                            }
                            return new StyleAttributes(effectiveRule.fontStyle, effectiveRule.foreground, effectiveRule.background);
                        }
                    }], [{
                        key: "createFromRawTheme",
                        value: function createFromRawTheme(source, colorMap) {
                            return this.createFromParsedTheme(parseTheme(source), colorMap);
                        }
                    }, {
                        key: "createFromParsedTheme",
                        value: function createFromParsedTheme(source, colorMap) {
                            return resolveParsedThemeRules(source, colorMap);
                        }
                    }]);
                }();
                var ScopeStack = /*#__PURE__*/function () {
                    function _ScopeStack(parent, scopeName) {
                        _classCallCheck(this, _ScopeStack);
                        this.parent = parent;
                        this.scopeName = scopeName;
                    }

                    return _createClass(_ScopeStack, [{
                        key: "push",
                        value: function push(scopeName) {
                            return new _ScopeStack(this, scopeName);
                        }
                    }, {
                        key: "getSegments",
                        value: function getSegments() {
                            var item = this;
                            var result = [];
                            while (item) {
                                result.push(item.scopeName);
                                item = item.parent;
                            }
                            result.reverse();
                            return result;
                        }
                    }, {
                        key: "toString",
                        value: function toString() {
                            return this.getSegments().join(" ");
                        }
                    }, {
                        key: "extends",
                        value: function _extends(other) {
                            if (this === other) {
                                return true;
                            }
                            if (this.parent === null) {
                                return false;
                            }
                            return this.parent.extends(other);
                        }
                    }, {
                        key: "getExtensionIfDefined",
                        value: function getExtensionIfDefined(base) {
                            var result = [];
                            var item = this;
                            while (item && item !== base) {
                                result.push(item.scopeName);
                                item = item.parent;
                            }
                            return item === base ? result.reverse() : void 0;
                        }
                    }], [{
                        key: "push",
                        value: function push(path, scopeNames) {
                            var _iterator = _createForOfIteratorHelper(scopeNames),
                                _step;
                            try {
                                for (_iterator.s(); !(_step = _iterator.n()).done;) {
                                    var name = _step.value;
                                    path = new _ScopeStack(path, name);
                                }
                            } catch (err) {
                                _iterator.e(err);
                            } finally {
                                _iterator.f();
                            }
                            return path;
                        }
                    }, {
                        key: "from",
                        value: function from() {
                            var result = null;
                            for (var i = 0; i < arguments.length; i++) {
                                result = new _ScopeStack(result, i < 0 || arguments.length <= i ? undefined : arguments[i]);
                            }
                            return result;
                        }
                    }]);
                }();

                function _scopePathMatchesParentScopes(scopePath, parentScopes) {
                    if (parentScopes.length === 0) {
                        return true;
                    }
                    for (var index = 0; index < parentScopes.length; index++) {
                        var scopePattern = parentScopes[index];
                        var scopeMustMatch = false;
                        if (scopePattern === ">") {
                            if (index === parentScopes.length - 1) {
                                return false;
                            }
                            scopePattern = parentScopes[++index];
                            scopeMustMatch = true;
                        }
                        while (scopePath) {
                            if (_matchesScope(scopePath.scopeName, scopePattern)) {
                                break;
                            }
                            if (scopeMustMatch) {
                                return false;
                            }
                            scopePath = scopePath.parent;
                        }
                        if (!scopePath) {
                            return false;
                        }
                        scopePath = scopePath.parent;
                    }
                    return true;
                }

                function _matchesScope(scopeName, scopePattern) {
                    return scopePattern === scopeName || scopeName.startsWith(scopePattern) && scopeName[scopePattern.length] === ".";
                }

                var StyleAttributes = /*#__PURE__*/_createClass(function StyleAttributes(fontStyle, foregroundId, backgroundId) {
                    _classCallCheck(this, StyleAttributes);
                    this.fontStyle = fontStyle;
                    this.foregroundId = foregroundId;
                    this.backgroundId = backgroundId;
                });

                function parseTheme(source) {
                    if (!source) {
                        return [];
                    }
                    if (!source.settings || !Array.isArray(source.settings)) {
                        return [];
                    }
                    var settings = source.settings;
                    var result = [],
                        resultLen = 0;
                    for (var i = 0, len = settings.length; i < len; i++) {
                        var entry = settings[i];
                        if (!entry.settings) {
                            continue;
                        }
                        var scopes = void 0;
                        if (typeof entry.scope === "string") {
                            var _scope = entry.scope;
                            _scope = _scope.replace(/^[,]+/, "");
                            _scope = _scope.replace(/[,]+$/, "");
                            scopes = _scope.split(",");
                        } else if (Array.isArray(entry.scope)) {
                            scopes = entry.scope;
                        } else {
                            scopes = [""];
                        }
                        var fontStyle = -1;
                        if (typeof entry.settings.fontStyle === "string") {
                            fontStyle = 0;
                            var segments = entry.settings.fontStyle.split(" ");
                            for (var j = 0, lenJ = segments.length; j < lenJ; j++) {
                                var segment = segments[j];
                                switch (segment) {
                                    case "italic":
                                        fontStyle = fontStyle | 1;
                                        break;
                                    case "bold":
                                        fontStyle = fontStyle | 2;
                                        break;
                                    case "underline":
                                        fontStyle = fontStyle | 4;
                                        break;
                                    case "strikethrough":
                                        fontStyle = fontStyle | 8;
                                        break;
                                }
                            }
                        }
                        var foreground = null;
                        if (typeof entry.settings.foreground === "string" && isValidHexColor(entry.settings.foreground)) {
                            foreground = entry.settings.foreground;
                        }
                        var background = null;
                        if (typeof entry.settings.background === "string" && isValidHexColor(entry.settings.background)) {
                            background = entry.settings.background;
                        }
                        for (var _j = 0, _lenJ = scopes.length; _j < _lenJ; _j++) {
                            var _scope2 = scopes[_j].trim();
                            var _segments = _scope2.split(" ");
                            var scope = _segments[_segments.length - 1];
                            var parentScopes = null;
                            if (_segments.length > 1) {
                                parentScopes = _segments.slice(0, _segments.length - 1);
                                parentScopes.reverse();
                            }
                            result[resultLen++] = new ParsedThemeRule(scope, parentScopes, i, fontStyle, foreground, background);
                        }
                    }
                    return result;
                }

                var ParsedThemeRule = /*#__PURE__*/_createClass(function ParsedThemeRule(scope, parentScopes, index, fontStyle, foreground, background) {
                    _classCallCheck(this, ParsedThemeRule);
                    this.scope = scope;
                    this.parentScopes = parentScopes;
                    this.index = index;
                    this.fontStyle = fontStyle;
                    this.foreground = foreground;
                    this.background = background;
                });
                var FontStyle = /* @__PURE__ */function (FontStyle2) {
                    FontStyle2[FontStyle2["NotSet"] = -1] = "NotSet";
                    FontStyle2[FontStyle2["None"] = 0] = "None";
                    FontStyle2[FontStyle2["Italic"] = 1] = "Italic";
                    FontStyle2[FontStyle2["Bold"] = 2] = "Bold";
                    FontStyle2[FontStyle2["Underline"] = 4] = "Underline";
                    FontStyle2[FontStyle2["Strikethrough"] = 8] = "Strikethrough";
                    return FontStyle2;
                }(FontStyle || {});

                function resolveParsedThemeRules(parsedThemeRules, _colorMap) {
                    parsedThemeRules.sort(function (a, b) {
                        var r = strcmp(a.scope, b.scope);
                        if (r !== 0) {
                            return r;
                        }
                        r = strArrCmp(a.parentScopes, b.parentScopes);
                        if (r !== 0) {
                            return r;
                        }
                        return a.index - b.index;
                    });
                    var defaultFontStyle = 0;
                    var defaultForeground = "#000000";
                    var defaultBackground = "#ffffff";
                    while (parsedThemeRules.length >= 1 && parsedThemeRules[0].scope === "") {
                        var incomingDefaults = parsedThemeRules.shift();
                        if (incomingDefaults.fontStyle !== -1) {
                            defaultFontStyle = incomingDefaults.fontStyle;
                        }
                        if (incomingDefaults.foreground !== null) {
                            defaultForeground = incomingDefaults.foreground;
                        }
                        if (incomingDefaults.background !== null) {
                            defaultBackground = incomingDefaults.background;
                        }
                    }
                    var colorMap = new ColorMap(_colorMap);
                    var defaults = new StyleAttributes(defaultFontStyle, colorMap.getId(defaultForeground), colorMap.getId(defaultBackground));
                    var root = new ThemeTrieElement(new ThemeTrieElementRule(0, null, -1, 0, 0), []);
                    for (var i = 0, len = parsedThemeRules.length; i < len; i++) {
                        var rule = parsedThemeRules[i];
                        root.insert(0, rule.scope, rule.parentScopes, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background));
                    }
                    return new Theme(colorMap, defaults, root);
                }

                var ColorMap = /*#__PURE__*/function () {
                    function ColorMap(_colorMap) {
                        _classCallCheck(this, ColorMap);
                        _defineProperty(this, "_isFrozen", void 0);
                        _defineProperty(this, "_lastColorId", void 0);
                        _defineProperty(this, "_id2color", void 0);
                        _defineProperty(this, "_color2id", void 0);
                        this._lastColorId = 0;
                        this._id2color = [];
                        this._color2id = /* @__PURE__ */Object.create(null);
                        if (Array.isArray(_colorMap)) {
                            this._isFrozen = true;
                            for (var i = 0, len = _colorMap.length; i < len; i++) {
                                this._color2id[_colorMap[i]] = i;
                                this._id2color[i] = _colorMap[i];
                            }
                        } else {
                            this._isFrozen = false;
                        }
                    }

                    return _createClass(ColorMap, [{
                        key: "getId",
                        value: function getId(color) {
                            if (color === null) {
                                return 0;
                            }
                            color = color.toUpperCase();
                            var value = this._color2id[color];
                            if (value) {
                                return value;
                            }
                            if (this._isFrozen) {
                                throw new Error("Missing color in color map - ".concat(color));
                            }
                            value = ++this._lastColorId;
                            this._color2id[color] = value;
                            this._id2color[value] = color;
                            return value;
                        }
                    }, {
                        key: "getColorMap",
                        value: function getColorMap() {
                            return this._id2color.slice(0);
                        }
                    }]);
                }();
                var emptyParentScopes = Object.freeze([]);
                var ThemeTrieElementRule = /*#__PURE__*/function () {
                    function _ThemeTrieElementRule(scopeDepth, parentScopes, fontStyle, foreground, background) {
                        _classCallCheck(this, _ThemeTrieElementRule);
                        _defineProperty(this, "scopeDepth", void 0);
                        _defineProperty(this, "parentScopes", void 0);
                        _defineProperty(this, "fontStyle", void 0);
                        _defineProperty(this, "foreground", void 0);
                        _defineProperty(this, "background", void 0);
                        this.scopeDepth = scopeDepth;
                        this.parentScopes = parentScopes || emptyParentScopes;
                        this.fontStyle = fontStyle;
                        this.foreground = foreground;
                        this.background = background;
                    }

                    return _createClass(_ThemeTrieElementRule, [{
                        key: "clone",
                        value: function clone() {
                            return new _ThemeTrieElementRule(this.scopeDepth, this.parentScopes, this.fontStyle, this.foreground, this.background);
                        }
                    }, {
                        key: "acceptOverwrite",
                        value: function acceptOverwrite(scopeDepth, fontStyle, foreground, background) {
                            if (this.scopeDepth > scopeDepth) {
                                console.log("how did this happen?");
                            } else {
                                this.scopeDepth = scopeDepth;
                            }
                            if (fontStyle !== -1) {
                                this.fontStyle = fontStyle;
                            }
                            if (foreground !== 0) {
                                this.foreground = foreground;
                            }
                            if (background !== 0) {
                                this.background = background;
                            }
                        }
                    }], [{
                        key: "cloneArr",
                        value: function cloneArr(arr) {
                            var r = [];
                            for (var i = 0, len = arr.length; i < len; i++) {
                                r[i] = arr[i].clone();
                            }
                            return r;
                        }
                    }]);
                }();
                var ThemeTrieElement = /*#__PURE__*/function () {
                    function _ThemeTrieElement(_mainRule) {
                        var rulesWithParentScopes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
                        var _children = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
                        _classCallCheck(this, _ThemeTrieElement);
                        _defineProperty(this, "_rulesWithParentScopes", void 0);
                        this._mainRule = _mainRule;
                        this._children = _children;
                        this._rulesWithParentScopes = rulesWithParentScopes;
                    }

                    return _createClass(_ThemeTrieElement, [{
                        key: "match",
                        value: function match(scope) {
                            if (scope !== "") {
                                var dotIndex = scope.indexOf(".");
                                var _head;
                                var tail;
                                if (dotIndex === -1) {
                                    _head = scope;
                                    tail = "";
                                } else {
                                    _head = scope.substring(0, dotIndex);
                                    tail = scope.substring(dotIndex + 1);
                                }
                                if (this._children.hasOwnProperty(_head)) {
                                    return this._children[_head].match(tail);
                                }
                            }
                            var rules = this._rulesWithParentScopes.concat(this._mainRule);
                            rules.sort(_ThemeTrieElement._cmpBySpecificity);
                            return rules;
                        }
                    }, {
                        key: "insert",
                        value: function insert(scopeDepth, scope, parentScopes, fontStyle, foreground, background) {
                            if (scope === "") {
                                this._doInsertHere(scopeDepth, parentScopes, fontStyle, foreground, background);
                                return;
                            }
                            var dotIndex = scope.indexOf(".");
                            var head;
                            var tail;
                            if (dotIndex === -1) {
                                head = scope;
                                tail = "";
                            } else {
                                head = scope.substring(0, dotIndex);
                                tail = scope.substring(dotIndex + 1);
                            }
                            var child;
                            if (this._children.hasOwnProperty(head)) {
                                child = this._children[head];
                            } else {
                                child = new _ThemeTrieElement(this._mainRule.clone(), ThemeTrieElementRule.cloneArr(this._rulesWithParentScopes));
                                this._children[head] = child;
                            }
                            child.insert(scopeDepth + 1, tail, parentScopes, fontStyle, foreground, background);
                        }
                    }, {
                        key: "_doInsertHere",
                        value: function _doInsertHere(scopeDepth, parentScopes, fontStyle, foreground, background) {
                            if (parentScopes === null) {
                                this._mainRule.acceptOverwrite(scopeDepth, fontStyle, foreground, background);
                                return;
                            }
                            for (var i = 0, len = this._rulesWithParentScopes.length; i < len; i++) {
                                var rule = this._rulesWithParentScopes[i];
                                if (strArrCmp(rule.parentScopes, parentScopes) === 0) {
                                    rule.acceptOverwrite(scopeDepth, fontStyle, foreground, background);
                                    return;
                                }
                            }
                            if (fontStyle === -1) {
                                fontStyle = this._mainRule.fontStyle;
                            }
                            if (foreground === 0) {
                                foreground = this._mainRule.foreground;
                            }
                            if (background === 0) {
                                background = this._mainRule.background;
                            }
                            this._rulesWithParentScopes.push(new ThemeTrieElementRule(scopeDepth, parentScopes, fontStyle, foreground, background));
                        }
                    }], [{
                        key: "_cmpBySpecificity",
                        value: function _cmpBySpecificity(a, b) {
                            if (a.scopeDepth !== b.scopeDepth) {
                                return b.scopeDepth - a.scopeDepth;
                            }
                            var aParentIndex = 0;
                            var bParentIndex = 0;
                            while (true) {
                                if (a.parentScopes[aParentIndex] === ">") {
                                    aParentIndex++;
                                }
                                if (b.parentScopes[bParentIndex] === ">") {
                                    bParentIndex++;
                                }
                                if (aParentIndex >= a.parentScopes.length || bParentIndex >= b.parentScopes.length) {
                                    break;
                                }
                                var parentScopeLengthDiff = b.parentScopes[bParentIndex].length - a.parentScopes[aParentIndex].length;
                                if (parentScopeLengthDiff !== 0) {
                                    return parentScopeLengthDiff;
                                }
                                aParentIndex++;
                                bParentIndex++;
                            }
                            return b.parentScopes.length - a.parentScopes.length;
                        }
                    }]);
                }();
                var EncodedTokenMetadata = /*#__PURE__*/function () {
                    function _EncodedTokenMetadata() {
                        _classCallCheck(this, _EncodedTokenMetadata);
                    }

                    return _createClass(_EncodedTokenMetadata, null, [{
                        key: "toBinaryStr",
                        value: function toBinaryStr(encodedTokenAttributes) {
                            return encodedTokenAttributes.toString(2).padStart(32, "0");
                        }
                    }, {
                        key: "print",
                        value: function print(encodedTokenAttributes) {
                            var languageId = _EncodedTokenMetadata.getLanguageId(encodedTokenAttributes);
                            var tokenType = _EncodedTokenMetadata.getTokenType(encodedTokenAttributes);
                            var fontStyle = _EncodedTokenMetadata.getFontStyle(encodedTokenAttributes);
                            var foreground = _EncodedTokenMetadata.getForeground(encodedTokenAttributes);
                            var background = _EncodedTokenMetadata.getBackground(encodedTokenAttributes);
                            console.log({
                                languageId: languageId,
                                tokenType: tokenType,
                                fontStyle: fontStyle,
                                foreground: foreground,
                                background: background
                            });
                        }
                    }, {
                        key: "getLanguageId",
                        value: function getLanguageId(encodedTokenAttributes) {
                            return (encodedTokenAttributes & 255) >>> 0;
                        }
                    }, {
                        key: "getTokenType",
                        value: function getTokenType(encodedTokenAttributes) {
                            return (encodedTokenAttributes & 768) >>> 8;
                        }
                    }, {
                        key: "containsBalancedBrackets",
                        value: function containsBalancedBrackets(encodedTokenAttributes) {
                            return (encodedTokenAttributes & 1024) !== 0;
                        }
                    }, {
                        key: "getFontStyle",
                        value: function getFontStyle(encodedTokenAttributes) {
                            return (encodedTokenAttributes & 30720) >>> 11;
                        }
                    }, {
                        key: "getForeground",
                        value: function getForeground(encodedTokenAttributes) {
                            return (encodedTokenAttributes & 16744448) >>> 15;
                        }
                    }, {
                        key: "getBackground",
                        value: function getBackground(encodedTokenAttributes) {
                            return (encodedTokenAttributes & 4278190080) >>> 24;
                        }
                        /**
                         * Updates the fields in `metadata`.
                         * A value of `0`, `NotSet` or `null` indicates that the corresponding field should be left as is.
                         */
                    }, {
                        key: "set",
                        value: function set(encodedTokenAttributes, languageId, tokenType, containsBalancedBrackets, fontStyle, foreground, background) {
                            var _languageId = _EncodedTokenMetadata.getLanguageId(encodedTokenAttributes);
                            var _tokenType = _EncodedTokenMetadata.getTokenType(encodedTokenAttributes);
                            var _containsBalancedBracketsBit = _EncodedTokenMetadata.containsBalancedBrackets(encodedTokenAttributes) ? 1 : 0;
                            var _fontStyle = _EncodedTokenMetadata.getFontStyle(encodedTokenAttributes);
                            var _foreground = _EncodedTokenMetadata.getForeground(encodedTokenAttributes);
                            var _background = _EncodedTokenMetadata.getBackground(encodedTokenAttributes);
                            if (languageId !== 0) {
                                _languageId = languageId;
                            }
                            if (tokenType !== 8) {
                                _tokenType = fromOptionalTokenType(tokenType);
                            }
                            if (containsBalancedBrackets !== null) {
                                _containsBalancedBracketsBit = containsBalancedBrackets ? 1 : 0;
                            }
                            if (fontStyle !== -1) {
                                _fontStyle = fontStyle;
                            }
                            if (foreground !== 0) {
                                _foreground = foreground;
                            }
                            if (background !== 0) {
                                _background = background;
                            }
                            return (_languageId << 0 | _tokenType << 8 | _containsBalancedBracketsBit << 10 | _fontStyle << 11 | _foreground << 15 | _background << 24) >>> 0;
                        }
                    }]);
                }();

                function toOptionalTokenType(standardType) {
                    return standardType;
                }

                function fromOptionalTokenType(standardType) {
                    return standardType;
                }

                function createMatchers(selector, matchesName) {
                    var results = [];
                    var tokenizer = newTokenizer(selector);
                    var token = tokenizer.next();
                    while (token !== null) {
                        var priority = 0;
                        if (token.length === 2 && token.charAt(1) === ":") {
                            switch (token.charAt(0)) {
                                case "R":
                                    priority = 1;
                                    break;
                                case "L":
                                    priority = -1;
                                    break;
                                default:
                                    console.log("Unknown priority ".concat(token, " in scope selector"));
                            }
                            token = tokenizer.next();
                        }
                        var matcher = parseConjunction();
                        results.push({
                            matcher: matcher,
                            priority: priority
                        });
                        if (token !== ",") {
                            break;
                        }
                        token = tokenizer.next();
                    }
                    return results;

                    function parseOperand() {
                        if (token === "-") {
                            token = tokenizer.next();
                            var expressionToNegate = parseOperand();
                            return function (matcherInput) {
                                return !!expressionToNegate && !expressionToNegate(matcherInput);
                            };
                        }
                        if (token === "(") {
                            token = tokenizer.next();
                            var expressionInParents = parseInnerExpression();
                            if (token === ")") {
                                token = tokenizer.next();
                            }
                            return expressionInParents;
                        }
                        if (isIdentifier(token)) {
                            var identifiers = [];
                            do {
                                identifiers.push(token);
                                token = tokenizer.next();
                            } while (isIdentifier(token));
                            return function (matcherInput) {
                                return matchesName(identifiers, matcherInput);
                            };
                        }
                        return null;
                    }

                    function parseConjunction() {
                        var matchers = [];
                        var matcher = parseOperand();
                        while (matcher) {
                            matchers.push(matcher);
                            matcher = parseOperand();
                        }
                        return function (matcherInput) {
                            return matchers.every(function (matcher2) {
                                return matcher2(matcherInput);
                            });
                        };
                    }

                    function parseInnerExpression() {
                        var matchers = [];
                        var matcher = parseConjunction();
                        while (matcher) {
                            matchers.push(matcher);
                            if (token === "|" || token === ",") {
                                do {
                                    token = tokenizer.next();
                                } while (token === "|" || token === ",");
                            } else {
                                break;
                            }
                            matcher = parseConjunction();
                        }
                        return function (matcherInput) {
                            return matchers.some(function (matcher2) {
                                return matcher2(matcherInput);
                            });
                        };
                    }
                }

                function isIdentifier(token) {
                    return !!token && !!token.match(/[\w\.:]+/);
                }

                function newTokenizer(input) {
                    var regex = /([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g;
                    var match = regex.exec(input);
                    return {
                        next: function next() {
                            if (!match) {
                                return null;
                            }
                            var res = match[0];
                            match = regex.exec(input);
                            return res;
                        }
                    };
                }

                function disposeOnigString(str) {
                    if (typeof str.dispose === "function") {
                        str.dispose();
                    }
                }

                var TopLevelRuleReference = /*#__PURE__*/function () {
                    function TopLevelRuleReference(scopeName) {
                        _classCallCheck(this, TopLevelRuleReference);
                        this.scopeName = scopeName;
                    }

                    return _createClass(TopLevelRuleReference, [{
                        key: "toKey",
                        value: function toKey() {
                            return this.scopeName;
                        }
                    }]);
                }();
                var TopLevelRepositoryRuleReference = /*#__PURE__*/function () {
                    function TopLevelRepositoryRuleReference(scopeName, ruleName) {
                        _classCallCheck(this, TopLevelRepositoryRuleReference);
                        this.scopeName = scopeName;
                        this.ruleName = ruleName;
                    }

                    return _createClass(TopLevelRepositoryRuleReference, [{
                        key: "toKey",
                        value: function toKey() {
                            return "".concat(this.scopeName, "#").concat(this.ruleName);
                        }
                    }]);
                }();
                var ExternalReferenceCollector = /*#__PURE__*/function () {
                    function ExternalReferenceCollector() {
                        _classCallCheck(this, ExternalReferenceCollector);
                        _defineProperty(this, "_references", []);
                        _defineProperty(this, "_seenReferenceKeys", /* @__PURE__ */new Set());
                        _defineProperty(this, "visitedRule", /* @__PURE__ */new Set());
                    }

                    return _createClass(ExternalReferenceCollector, [{
                        key: "references",
                        get: function get() {
                            return this._references;
                        }
                    }, {
                        key: "add",
                        value: function add(reference) {
                            var key = reference.toKey();
                            if (this._seenReferenceKeys.has(key)) {
                                return;
                            }
                            this._seenReferenceKeys.add(key);
                            this._references.push(reference);
                        }
                    }]);
                }();
                var ScopeDependencyProcessor = /*#__PURE__*/function () {
                    function ScopeDependencyProcessor(repo, initialScopeName) {
                        _classCallCheck(this, ScopeDependencyProcessor);
                        _defineProperty(this, "seenFullScopeRequests", /* @__PURE__ */new Set());
                        _defineProperty(this, "seenPartialScopeRequests", /* @__PURE__ */new Set());
                        _defineProperty(this, "Q", void 0);
                        this.repo = repo;
                        this.initialScopeName = initialScopeName;
                        this.seenFullScopeRequests.add(this.initialScopeName);
                        this.Q = [new TopLevelRuleReference(this.initialScopeName)];
                    }

                    return _createClass(ScopeDependencyProcessor, [{
                        key: "processQueue",
                        value: function processQueue() {
                            var q = this.Q;
                            this.Q = [];
                            var deps = new ExternalReferenceCollector();
                            var _iterator2 = _createForOfIteratorHelper(q),
                                _step2;
                            try {
                                for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
                                    var dep = _step2.value;
                                    collectReferencesOfReference(dep, this.initialScopeName, this.repo, deps);
                                }
                            } catch (err) {
                                _iterator2.e(err);
                            } finally {
                                _iterator2.f();
                            }
                            var _iterator3 = _createForOfIteratorHelper(deps.references),
                                _step3;
                            try {
                                for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
                                    var _dep = _step3.value;
                                    if (_dep instanceof TopLevelRuleReference) {
                                        if (this.seenFullScopeRequests.has(_dep.scopeName)) {
                                            continue;
                                        }
                                        this.seenFullScopeRequests.add(_dep.scopeName);
                                        this.Q.push(_dep);
                                    } else {
                                        if (this.seenFullScopeRequests.has(_dep.scopeName)) {
                                            continue;
                                        }
                                        if (this.seenPartialScopeRequests.has(_dep.toKey())) {
                                            continue;
                                        }
                                        this.seenPartialScopeRequests.add(_dep.toKey());
                                        this.Q.push(_dep);
                                    }
                                }
                            } catch (err) {
                                _iterator3.e(err);
                            } finally {
                                _iterator3.f();
                            }
                        }
                    }]);
                }();

                function collectReferencesOfReference(reference, baseGrammarScopeName, repo, result) {
                    var selfGrammar = repo.lookup(reference.scopeName);
                    if (!selfGrammar) {
                        if (reference.scopeName === baseGrammarScopeName) {
                            throw new Error("No grammar provided for <".concat(baseGrammarScopeName, ">"));
                        }
                        return;
                    }
                    var baseGrammar = repo.lookup(baseGrammarScopeName);
                    if (reference instanceof TopLevelRuleReference) {
                        collectExternalReferencesInTopLevelRule({
                            baseGrammar: baseGrammar,
                            selfGrammar: selfGrammar
                        }, result);
                    } else {
                        collectExternalReferencesInTopLevelRepositoryRule(reference.ruleName, {
                            baseGrammar: baseGrammar,
                            selfGrammar: selfGrammar,
                            repository: selfGrammar.repository
                        }, result);
                    }
                    var injections = repo.injections(reference.scopeName);
                    if (injections) {
                        var _iterator4 = _createForOfIteratorHelper(injections),
                            _step4;
                        try {
                            for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
                                var injection = _step4.value;
                                result.add(new TopLevelRuleReference(injection));
                            }
                        } catch (err) {
                            _iterator4.e(err);
                        } finally {
                            _iterator4.f();
                        }
                    }
                }

                function collectExternalReferencesInTopLevelRepositoryRule(ruleName, context, result) {
                    if (context.repository && context.repository[ruleName]) {
                        var rule = context.repository[ruleName];
                        collectExternalReferencesInRules([rule], context, result);
                    }
                }

                function collectExternalReferencesInTopLevelRule(context, result) {
                    if (context.selfGrammar.patterns && Array.isArray(context.selfGrammar.patterns)) {
                        collectExternalReferencesInRules(context.selfGrammar.patterns, _objectSpread(_objectSpread({}, context), {}, {
                            repository: context.selfGrammar.repository
                        }), result);
                    }
                    if (context.selfGrammar.injections) {
                        collectExternalReferencesInRules(Object.values(context.selfGrammar.injections), _objectSpread(_objectSpread({}, context), {}, {
                            repository: context.selfGrammar.repository
                        }), result);
                    }
                }

                function collectExternalReferencesInRules(rules, context, result) {
                    var _iterator5 = _createForOfIteratorHelper(rules),
                        _step5;
                    try {
                        for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
                            var rule = _step5.value;
                            if (result.visitedRule.has(rule)) {
                                continue;
                            }
                            result.visitedRule.add(rule);
                            var patternRepository = rule.repository ? mergeObjects({}, context.repository, rule.repository) : context.repository;
                            if (Array.isArray(rule.patterns)) {
                                collectExternalReferencesInRules(rule.patterns, _objectSpread(_objectSpread({}, context), {}, {
                                    repository: patternRepository
                                }), result);
                            }
                            var include = rule.include;
                            if (!include) {
                                continue;
                            }
                            var reference = parseInclude(include);
                            switch (reference.kind) {
                                case 0:
                                    collectExternalReferencesInTopLevelRule(_objectSpread(_objectSpread({}, context), {}, {
                                        selfGrammar: context.baseGrammar
                                    }), result);
                                    break;
                                case 1:
                                    collectExternalReferencesInTopLevelRule(context, result);
                                    break;
                                case 2:
                                    collectExternalReferencesInTopLevelRepositoryRule(reference.ruleName, _objectSpread(_objectSpread({}, context), {}, {
                                        repository: patternRepository
                                    }), result);
                                    break;
                                case 3:
                                case 4:
                                    var selfGrammar = reference.scopeName === context.selfGrammar.scopeName ? context.selfGrammar : reference.scopeName === context.baseGrammar.scopeName ? context.baseGrammar : void 0;
                                    if (selfGrammar) {
                                        var newContext = {
                                            baseGrammar: context.baseGrammar,
                                            selfGrammar: selfGrammar,
                                            repository: patternRepository
                                        };
                                        if (reference.kind === 4) {
                                            collectExternalReferencesInTopLevelRepositoryRule(reference.ruleName, newContext, result);
                                        } else {
                                            collectExternalReferencesInTopLevelRule(newContext, result);
                                        }
                                    } else {
                                        if (reference.kind === 4) {
                                            result.add(new TopLevelRepositoryRuleReference(reference.scopeName, reference.ruleName));
                                        } else {
                                            result.add(new TopLevelRuleReference(reference.scopeName));
                                        }
                                    }
                                    break;
                            }
                        }
                    } catch (err) {
                        _iterator5.e(err);
                    } finally {
                        _iterator5.f();
                    }
                }

                var BaseReference = /*#__PURE__*/_createClass(function BaseReference() {
                    _classCallCheck(this, BaseReference);
                    _defineProperty(this, "kind", 0);
                });
                var SelfReference = /*#__PURE__*/_createClass(function SelfReference() {
                    _classCallCheck(this, SelfReference);
                    _defineProperty(this, "kind", 1);
                });
                var RelativeReference = /*#__PURE__*/_createClass(function RelativeReference(ruleName) {
                    _classCallCheck(this, RelativeReference);
                    _defineProperty(this, "kind", 2);
                    this.ruleName = ruleName;
                });
                var TopLevelReference = /*#__PURE__*/_createClass(function TopLevelReference(scopeName) {
                    _classCallCheck(this, TopLevelReference);
                    _defineProperty(this, "kind", 3);
                    this.scopeName = scopeName;
                });
                var TopLevelRepositoryReference = /*#__PURE__*/_createClass(function TopLevelRepositoryReference(scopeName, ruleName) {
                    _classCallCheck(this, TopLevelRepositoryReference);
                    _defineProperty(this, "kind", 4);
                    this.scopeName = scopeName;
                    this.ruleName = ruleName;
                });

                function parseInclude(include) {
                    if (include === "$base") {
                        return new BaseReference();
                    } else if (include === "$self") {
                        return new SelfReference();
                    }
                    var indexOfSharp = include.indexOf("#");
                    if (indexOfSharp === -1) {
                        return new TopLevelReference(include);
                    } else if (indexOfSharp === 0) {
                        return new RelativeReference(include.substring(1));
                    } else {
                        var scopeName = include.substring(0, indexOfSharp);
                        var ruleName = include.substring(indexOfSharp + 1);
                        return new TopLevelRepositoryReference(scopeName, ruleName);
                    }
                }

                var HAS_BACK_REFERENCES = /\\(\d+)/;
                var BACK_REFERENCING_END = /\\(\d+)/g;
                var endRuleId = -1;
                var whileRuleId = -2;

                function ruleIdFromNumber(id) {
                    return id;
                }

                function ruleIdToNumber(id) {
                    return id;
                }

                var Rule = /*#__PURE__*/function () {
                    function Rule($location, id, name, contentName) {
                        _classCallCheck(this, Rule);
                        _defineProperty(this, "$location", void 0);
                        _defineProperty(this, "id", void 0);
                        _defineProperty(this, "_nameIsCapturing", void 0);
                        _defineProperty(this, "_name", void 0);
                        _defineProperty(this, "_contentNameIsCapturing", void 0);
                        _defineProperty(this, "_contentName", void 0);
                        this.$location = $location;
                        this.id = id;
                        this._name = name || null;
                        this._nameIsCapturing = RegexSource.hasCaptures(this._name);
                        this._contentName = contentName || null;
                        this._contentNameIsCapturing = RegexSource.hasCaptures(this._contentName);
                    }

                    return _createClass(Rule, [{
                        key: "debugName",
                        get: function get() {
                            var location = this.$location ? "".concat(basename(this.$location.filename), ":").concat(this.$location.line) : "unknown";
                            return "".concat(this.constructor.name, "#").concat(this.id, " @ ").concat(location);
                        }
                    }, {
                        key: "getName",
                        value: function getName(lineText, captureIndices) {
                            if (!this._nameIsCapturing || this._name === null || lineText === null || captureIndices === null) {
                                return this._name;
                            }
                            return RegexSource.replaceCaptures(this._name, lineText, captureIndices);
                        }
                    }, {
                        key: "getContentName",
                        value: function getContentName(lineText, captureIndices) {
                            if (!this._contentNameIsCapturing || this._contentName === null) {
                                return this._contentName;
                            }
                            return RegexSource.replaceCaptures(this._contentName, lineText, captureIndices);
                        }
                    }]);
                }();
                var CaptureRule = /*#__PURE__*/function (_Rule) {
                    function CaptureRule($location, id, name, contentName, retokenizeCapturedWithRuleId) {
                        var _this4;
                        _classCallCheck(this, CaptureRule);
                        _this4 = _callSuper(this, CaptureRule, [$location, id, name, contentName]);
                        _defineProperty(_this4, "retokenizeCapturedWithRuleId", void 0);
                        _this4.retokenizeCapturedWithRuleId = retokenizeCapturedWithRuleId;
                        return _this4;
                    }

                    _inherits(CaptureRule, _Rule);
                    return _createClass(CaptureRule, [{
                        key: "dispose",
                        value: function dispose() {
                        }
                    }, {
                        key: "collectPatterns",
                        value: function collectPatterns(grammar, out) {
                            throw new Error("Not supported!");
                        }
                    }, {
                        key: "compile",
                        value: function compile(grammar, endRegexSource) {
                            throw new Error("Not supported!");
                        }
                    }, {
                        key: "compileAG",
                        value: function compileAG(grammar, endRegexSource, allowA, allowG) {
                            throw new Error("Not supported!");
                        }
                    }]);
                }(Rule);
                var MatchRule = /*#__PURE__*/function (_Rule2) {
                    function MatchRule($location, id, name, match, captures) {
                        var _this5;
                        _classCallCheck(this, MatchRule);
                        _this5 = _callSuper(this, MatchRule, [$location, id, name, null]);
                        _defineProperty(_this5, "_match", void 0);
                        _defineProperty(_this5, "captures", void 0);
                        _defineProperty(_this5, "_cachedCompiledPatterns", void 0);
                        _this5._match = new RegExpSource(match, _this5.id);
                        _this5.captures = captures;
                        _this5._cachedCompiledPatterns = null;
                        return _this5;
                    }

                    _inherits(MatchRule, _Rule2);
                    return _createClass(MatchRule, [{
                        key: "dispose",
                        value: function dispose() {
                            if (this._cachedCompiledPatterns) {
                                this._cachedCompiledPatterns.dispose();
                                this._cachedCompiledPatterns = null;
                            }
                        }
                    }, {
                        key: "debugMatchRegExp",
                        get: function get() {
                            return "".concat(this._match.source);
                        }
                    }, {
                        key: "collectPatterns",
                        value: function collectPatterns(grammar, out) {
                            out.push(this._match);
                        }
                    }, {
                        key: "compile",
                        value: function compile(grammar, endRegexSource) {
                            return this._getCachedCompiledPatterns(grammar).compile(grammar);
                        }
                    }, {
                        key: "compileAG",
                        value: function compileAG(grammar, endRegexSource, allowA, allowG) {
                            return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);
                        }
                    }, {
                        key: "_getCachedCompiledPatterns",
                        value: function _getCachedCompiledPatterns(grammar) {
                            if (!this._cachedCompiledPatterns) {
                                this._cachedCompiledPatterns = new RegExpSourceList();
                                this.collectPatterns(grammar, this._cachedCompiledPatterns);
                            }
                            return this._cachedCompiledPatterns;
                        }
                    }]);
                }(Rule);
                var IncludeOnlyRule = /*#__PURE__*/function (_Rule3) {
                    function IncludeOnlyRule($location, id, name, contentName, patterns) {
                        var _this6;
                        _classCallCheck(this, IncludeOnlyRule);
                        _this6 = _callSuper(this, IncludeOnlyRule, [$location, id, name, contentName]);
                        _defineProperty(_this6, "hasMissingPatterns", void 0);
                        _defineProperty(_this6, "patterns", void 0);
                        _defineProperty(_this6, "_cachedCompiledPatterns", void 0);
                        _this6.patterns = patterns.patterns;
                        _this6.hasMissingPatterns = patterns.hasMissingPatterns;
                        _this6._cachedCompiledPatterns = null;
                        return _this6;
                    }

                    _inherits(IncludeOnlyRule, _Rule3);
                    return _createClass(IncludeOnlyRule, [{
                        key: "dispose",
                        value: function dispose() {
                            if (this._cachedCompiledPatterns) {
                                this._cachedCompiledPatterns.dispose();
                                this._cachedCompiledPatterns = null;
                            }
                        }
                    }, {
                        key: "collectPatterns",
                        value: function collectPatterns(grammar, out) {
                            var _iterator6 = _createForOfIteratorHelper(this.patterns),
                                _step6;
                            try {
                                for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
                                    var pattern = _step6.value;
                                    var rule = grammar.getRule(pattern);
                                    rule.collectPatterns(grammar, out);
                                }
                            } catch (err) {
                                _iterator6.e(err);
                            } finally {
                                _iterator6.f();
                            }
                        }
                    }, {
                        key: "compile",
                        value: function compile(grammar, endRegexSource) {
                            return this._getCachedCompiledPatterns(grammar).compile(grammar);
                        }
                    }, {
                        key: "compileAG",
                        value: function compileAG(grammar, endRegexSource, allowA, allowG) {
                            return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);
                        }
                    }, {
                        key: "_getCachedCompiledPatterns",
                        value: function _getCachedCompiledPatterns(grammar) {
                            if (!this._cachedCompiledPatterns) {
                                this._cachedCompiledPatterns = new RegExpSourceList();
                                this.collectPatterns(grammar, this._cachedCompiledPatterns);
                            }
                            return this._cachedCompiledPatterns;
                        }
                    }]);
                }(Rule);
                var BeginEndRule = /*#__PURE__*/function (_Rule4) {
                    function BeginEndRule($location, id, name, contentName, begin, beginCaptures, end, endCaptures, applyEndPatternLast, patterns) {
                        var _this7;
                        _classCallCheck(this, BeginEndRule);
                        _this7 = _callSuper(this, BeginEndRule, [$location, id, name, contentName]);
                        _defineProperty(_this7, "_begin", void 0);
                        _defineProperty(_this7, "beginCaptures", void 0);
                        _defineProperty(_this7, "_end", void 0);
                        _defineProperty(_this7, "endHasBackReferences", void 0);
                        _defineProperty(_this7, "endCaptures", void 0);
                        _defineProperty(_this7, "applyEndPatternLast", void 0);
                        _defineProperty(_this7, "hasMissingPatterns", void 0);
                        _defineProperty(_this7, "patterns", void 0);
                        _defineProperty(_this7, "_cachedCompiledPatterns", void 0);
                        _this7._begin = new RegExpSource(begin, _this7.id);
                        _this7.beginCaptures = beginCaptures;
                        _this7._end = new RegExpSource(end ? end : "￿", -1);
                        _this7.endHasBackReferences = _this7._end.hasBackReferences;
                        _this7.endCaptures = endCaptures;
                        _this7.applyEndPatternLast = applyEndPatternLast || false;
                        _this7.patterns = patterns.patterns;
                        _this7.hasMissingPatterns = patterns.hasMissingPatterns;
                        _this7._cachedCompiledPatterns = null;
                        return _this7;
                    }

                    _inherits(BeginEndRule, _Rule4);
                    return _createClass(BeginEndRule, [{
                        key: "dispose",
                        value: function dispose() {
                            if (this._cachedCompiledPatterns) {
                                this._cachedCompiledPatterns.dispose();
                                this._cachedCompiledPatterns = null;
                            }
                        }
                    }, {
                        key: "debugBeginRegExp",
                        get: function get() {
                            return "".concat(this._begin.source);
                        }
                    }, {
                        key: "debugEndRegExp",
                        get: function get() {
                            return "".concat(this._end.source);
                        }
                    }, {
                        key: "getEndWithResolvedBackReferences",
                        value: function getEndWithResolvedBackReferences(lineText, captureIndices) {
                            return this._end.resolveBackReferences(lineText, captureIndices);
                        }
                    }, {
                        key: "collectPatterns",
                        value: function collectPatterns(grammar, out) {
                            out.push(this._begin);
                        }
                    }, {
                        key: "compile",
                        value: function compile(grammar, endRegexSource) {
                            return this._getCachedCompiledPatterns(grammar, endRegexSource).compile(grammar);
                        }
                    }, {
                        key: "compileAG",
                        value: function compileAG(grammar, endRegexSource, allowA, allowG) {
                            return this._getCachedCompiledPatterns(grammar, endRegexSource).compileAG(grammar, allowA, allowG);
                        }
                    }, {
                        key: "_getCachedCompiledPatterns",
                        value: function _getCachedCompiledPatterns(grammar, endRegexSource) {
                            if (!this._cachedCompiledPatterns) {
                                this._cachedCompiledPatterns = new RegExpSourceList();
                                var _iterator7 = _createForOfIteratorHelper(this.patterns),
                                    _step7;
                                try {
                                    for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
                                        var pattern = _step7.value;
                                        var rule = grammar.getRule(pattern);
                                        rule.collectPatterns(grammar, this._cachedCompiledPatterns);
                                    }
                                } catch (err) {
                                    _iterator7.e(err);
                                } finally {
                                    _iterator7.f();
                                }
                                if (this.applyEndPatternLast) {
                                    this._cachedCompiledPatterns.push(this._end.hasBackReferences ? this._end.clone() : this._end);
                                } else {
                                    this._cachedCompiledPatterns.unshift(this._end.hasBackReferences ? this._end.clone() : this._end);
                                }
                            }
                            if (this._end.hasBackReferences) {
                                if (this.applyEndPatternLast) {
                                    this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length() - 1, endRegexSource);
                                } else {
                                    this._cachedCompiledPatterns.setSource(0, endRegexSource);
                                }
                            }
                            return this._cachedCompiledPatterns;
                        }
                    }]);
                }(Rule);
                var BeginWhileRule = /*#__PURE__*/function (_Rule5) {
                    function BeginWhileRule($location, id, name, contentName, begin, beginCaptures, _while, whileCaptures, patterns) {
                        var _this8;
                        _classCallCheck(this, BeginWhileRule);
                        _this8 = _callSuper(this, BeginWhileRule, [$location, id, name, contentName]);
                        _defineProperty(_this8, "_begin", void 0);
                        _defineProperty(_this8, "beginCaptures", void 0);
                        _defineProperty(_this8, "whileCaptures", void 0);
                        _defineProperty(_this8, "_while", void 0);
                        _defineProperty(_this8, "whileHasBackReferences", void 0);
                        _defineProperty(_this8, "hasMissingPatterns", void 0);
                        _defineProperty(_this8, "patterns", void 0);
                        _defineProperty(_this8, "_cachedCompiledPatterns", void 0);
                        _defineProperty(_this8, "_cachedCompiledWhilePatterns", void 0);
                        _this8._begin = new RegExpSource(begin, _this8.id);
                        _this8.beginCaptures = beginCaptures;
                        _this8.whileCaptures = whileCaptures;
                        _this8._while = new RegExpSource(_while, whileRuleId);
                        _this8.whileHasBackReferences = _this8._while.hasBackReferences;
                        _this8.patterns = patterns.patterns;
                        _this8.hasMissingPatterns = patterns.hasMissingPatterns;
                        _this8._cachedCompiledPatterns = null;
                        _this8._cachedCompiledWhilePatterns = null;
                        return _this8;
                    }

                    _inherits(BeginWhileRule, _Rule5);
                    return _createClass(BeginWhileRule, [{
                        key: "dispose",
                        value: function dispose() {
                            if (this._cachedCompiledPatterns) {
                                this._cachedCompiledPatterns.dispose();
                                this._cachedCompiledPatterns = null;
                            }
                            if (this._cachedCompiledWhilePatterns) {
                                this._cachedCompiledWhilePatterns.dispose();
                                this._cachedCompiledWhilePatterns = null;
                            }
                        }
                    }, {
                        key: "debugBeginRegExp",
                        get: function get() {
                            return "".concat(this._begin.source);
                        }
                    }, {
                        key: "debugWhileRegExp",
                        get: function get() {
                            return "".concat(this._while.source);
                        }
                    }, {
                        key: "getWhileWithResolvedBackReferences",
                        value: function getWhileWithResolvedBackReferences(lineText, captureIndices) {
                            return this._while.resolveBackReferences(lineText, captureIndices);
                        }
                    }, {
                        key: "collectPatterns",
                        value: function collectPatterns(grammar, out) {
                            out.push(this._begin);
                        }
                    }, {
                        key: "compile",
                        value: function compile(grammar, endRegexSource) {
                            return this._getCachedCompiledPatterns(grammar).compile(grammar);
                        }
                    }, {
                        key: "compileAG",
                        value: function compileAG(grammar, endRegexSource, allowA, allowG) {
                            return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);
                        }
                    }, {
                        key: "_getCachedCompiledPatterns",
                        value: function _getCachedCompiledPatterns(grammar) {
                            if (!this._cachedCompiledPatterns) {
                                this._cachedCompiledPatterns = new RegExpSourceList();
                                var _iterator8 = _createForOfIteratorHelper(this.patterns),
                                    _step8;
                                try {
                                    for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
                                        var pattern = _step8.value;
                                        var rule = grammar.getRule(pattern);
                                        rule.collectPatterns(grammar, this._cachedCompiledPatterns);
                                    }
                                } catch (err) {
                                    _iterator8.e(err);
                                } finally {
                                    _iterator8.f();
                                }
                            }
                            return this._cachedCompiledPatterns;
                        }
                    }, {
                        key: "compileWhile",
                        value: function compileWhile(grammar, endRegexSource) {
                            return this._getCachedCompiledWhilePatterns(grammar, endRegexSource).compile(grammar);
                        }
                    }, {
                        key: "compileWhileAG",
                        value: function compileWhileAG(grammar, endRegexSource, allowA, allowG) {
                            return this._getCachedCompiledWhilePatterns(grammar, endRegexSource).compileAG(grammar, allowA, allowG);
                        }
                    }, {
                        key: "_getCachedCompiledWhilePatterns",
                        value: function _getCachedCompiledWhilePatterns(grammar, endRegexSource) {
                            if (!this._cachedCompiledWhilePatterns) {
                                this._cachedCompiledWhilePatterns = new RegExpSourceList();
                                this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences ? this._while.clone() : this._while);
                            }
                            if (this._while.hasBackReferences) {
                                this._cachedCompiledWhilePatterns.setSource(0, endRegexSource ? endRegexSource : "￿");
                            }
                            return this._cachedCompiledWhilePatterns;
                        }
                    }]);
                }(Rule);
                var RuleFactory = /*#__PURE__*/function () {
                    function _RuleFactory() {
                        _classCallCheck(this, _RuleFactory);
                    }

                    return _createClass(_RuleFactory, null, [{
                        key: "createCaptureRule",
                        value: function createCaptureRule(helper, $location, name, contentName, retokenizeCapturedWithRuleId) {
                            return helper.registerRule(function (id) {
                                return new CaptureRule($location, id, name, contentName, retokenizeCapturedWithRuleId);
                            });
                        }
                    }, {
                        key: "getCompiledRuleId",
                        value: function getCompiledRuleId(desc, helper, repository) {
                            if (!desc.id) {
                                helper.registerRule(function (id) {
                                    desc.id = id;
                                    if (desc.match) {
                                        return new MatchRule(desc.$vscodeTextmateLocation, desc.id, desc.name, desc.match, _RuleFactory._compileCaptures(desc.captures, helper, repository));
                                    }
                                    if (typeof desc.begin === "undefined") {
                                        if (desc.repository) {
                                            repository = mergeObjects({}, repository, desc.repository);
                                        }
                                        var patterns = desc.patterns;
                                        if (typeof patterns === "undefined" && desc.include) {
                                            patterns = [{
                                                include: desc.include
                                            }];
                                        }
                                        return new IncludeOnlyRule(desc.$vscodeTextmateLocation, desc.id, desc.name, desc.contentName, _RuleFactory._compilePatterns(patterns, helper, repository));
                                    }
                                    if (desc.while) {
                                        return new BeginWhileRule(desc.$vscodeTextmateLocation, desc.id, desc.name, desc.contentName, desc.begin, _RuleFactory._compileCaptures(desc.beginCaptures || desc.captures, helper, repository), desc.while, _RuleFactory._compileCaptures(desc.whileCaptures || desc.captures, helper, repository), _RuleFactory._compilePatterns(desc.patterns, helper, repository));
                                    }
                                    return new BeginEndRule(desc.$vscodeTextmateLocation, desc.id, desc.name, desc.contentName, desc.begin, _RuleFactory._compileCaptures(desc.beginCaptures || desc.captures, helper, repository), desc.end, _RuleFactory._compileCaptures(desc.endCaptures || desc.captures, helper, repository), desc.applyEndPatternLast, _RuleFactory._compilePatterns(desc.patterns, helper, repository));
                                });
                            }
                            return desc.id;
                        }
                    }, {
                        key: "_compileCaptures",
                        value: function _compileCaptures(captures, helper, repository) {
                            var r = [];
                            if (captures) {
                                var maximumCaptureId = 0;
                                for (var captureId in captures) {
                                    if (captureId === "$vscodeTextmateLocation") {
                                        continue;
                                    }
                                    var numericCaptureId = parseInt(captureId, 10);
                                    if (numericCaptureId > maximumCaptureId) {
                                        maximumCaptureId = numericCaptureId;
                                    }
                                }
                                for (var i = 0; i <= maximumCaptureId; i++) {
                                    r[i] = null;
                                }
                                for (var _captureId in captures) {
                                    if (_captureId === "$vscodeTextmateLocation") {
                                        continue;
                                    }
                                    var _numericCaptureId = parseInt(_captureId, 10);
                                    var retokenizeCapturedWithRuleId = 0;
                                    if (captures[_captureId].patterns) {
                                        retokenizeCapturedWithRuleId = _RuleFactory.getCompiledRuleId(captures[_captureId], helper, repository);
                                    }
                                    r[_numericCaptureId] = _RuleFactory.createCaptureRule(helper, captures[_captureId].$vscodeTextmateLocation, captures[_captureId].name, captures[_captureId].contentName, retokenizeCapturedWithRuleId);
                                }
                            }
                            return r;
                        }
                    }, {
                        key: "_compilePatterns",
                        value: function _compilePatterns(patterns, helper, repository) {
                            var r = [];
                            if (patterns) {
                                for (var i = 0, len = patterns.length; i < len; i++) {
                                    var pattern = patterns[i];
                                    var ruleId = -1;
                                    if (pattern.include) {
                                        var reference = parseInclude(pattern.include);
                                        switch (reference.kind) {
                                            case 0:
                                            case 1:
                                                ruleId = _RuleFactory.getCompiledRuleId(repository[pattern.include], helper, repository);
                                                break;
                                            case 2:
                                                var localIncludedRule = repository[reference.ruleName];
                                                if (localIncludedRule) {
                                                    ruleId = _RuleFactory.getCompiledRuleId(localIncludedRule, helper, repository);
                                                }
                                                break;
                                            case 3:
                                            case 4:
                                                var externalGrammarName = reference.scopeName;
                                                var externalGrammarInclude = reference.kind === 4 ? reference.ruleName : null;
                                                var externalGrammar = helper.getExternalGrammar(externalGrammarName, repository);
                                                if (externalGrammar) {
                                                    if (externalGrammarInclude) {
                                                        var externalIncludedRule = externalGrammar.repository[externalGrammarInclude];
                                                        if (externalIncludedRule) {
                                                            ruleId = _RuleFactory.getCompiledRuleId(externalIncludedRule, helper, externalGrammar.repository);
                                                        }
                                                    } else {
                                                        ruleId = _RuleFactory.getCompiledRuleId(externalGrammar.repository.$self, helper, externalGrammar.repository);
                                                    }
                                                }
                                                break;
                                        }
                                    } else {
                                        ruleId = _RuleFactory.getCompiledRuleId(pattern, helper, repository);
                                    }
                                    if (ruleId !== -1) {
                                        var rule = helper.getRule(ruleId);
                                        var skipRule = false;
                                        if (rule instanceof IncludeOnlyRule || rule instanceof BeginEndRule || rule instanceof BeginWhileRule) {
                                            if (rule.hasMissingPatterns && rule.patterns.length === 0) {
                                                skipRule = true;
                                            }
                                        }
                                        if (skipRule) {
                                            continue;
                                        }
                                        r.push(ruleId);
                                    }
                                }
                            }
                            return {
                                patterns: r,
                                hasMissingPatterns: (patterns ? patterns.length : 0) !== r.length
                            };
                        }
                    }]);
                }();
                var RegExpSource = /*#__PURE__*/function () {
                    function _RegExpSource(regExpSource, ruleId) {
                        _classCallCheck(this, _RegExpSource);
                        _defineProperty(this, "source", void 0);
                        _defineProperty(this, "ruleId", void 0);
                        _defineProperty(this, "hasAnchor", void 0);
                        _defineProperty(this, "hasBackReferences", void 0);
                        _defineProperty(this, "_anchorCache", void 0);
                        if (regExpSource && typeof regExpSource === "string") {
                            var len = regExpSource.length;
                            var lastPushedPos = 0;
                            var output = [];
                            var hasAnchor = false;
                            for (var pos = 0; pos < len; pos++) {
                                var ch = regExpSource.charAt(pos);
                                if (ch === "\\") {
                                    if (pos + 1 < len) {
                                        var nextCh = regExpSource.charAt(pos + 1);
                                        if (nextCh === "z") {
                                            output.push(regExpSource.substring(lastPushedPos, pos));
                                            output.push("$(?!\\n)(?<!\\n)");
                                            lastPushedPos = pos + 2;
                                        } else if (nextCh === "A" || nextCh === "G") {
                                            hasAnchor = true;
                                        }
                                        pos++;
                                    }
                                }
                            }
                            this.hasAnchor = hasAnchor;
                            if (lastPushedPos === 0) {
                                this.source = regExpSource;
                            } else {
                                output.push(regExpSource.substring(lastPushedPos, len));
                                this.source = output.join("");
                            }
                        } else {
                            this.hasAnchor = false;
                            this.source = regExpSource;
                        }
                        if (this.hasAnchor) {
                            this._anchorCache = this._buildAnchorCache();
                        } else {
                            this._anchorCache = null;
                        }
                        this.ruleId = ruleId;
                        if (typeof this.source === "string") {
                            this.hasBackReferences = HAS_BACK_REFERENCES.test(this.source);
                        } else {
                            this.hasBackReferences = false;
                        }
                    }

                    return _createClass(_RegExpSource, [{
                        key: "clone",
                        value: function clone() {
                            return new _RegExpSource(this.source, this.ruleId);
                        }
                    }, {
                        key: "setSource",
                        value: function setSource(newSource) {
                            if (this.source === newSource) {
                                return;
                            }
                            this.source = newSource;
                            if (this.hasAnchor) {
                                this._anchorCache = this._buildAnchorCache();
                            }
                        }
                    }, {
                        key: "resolveBackReferences",
                        value: function resolveBackReferences(lineText, captureIndices) {
                            if (typeof this.source !== "string") {
                                throw new Error("This method should only be called if the source is a string");
                            }
                            var capturedValues = captureIndices.map(function (capture) {
                                return lineText.substring(capture.start, capture.end);
                            });
                            BACK_REFERENCING_END.lastIndex = 0;
                            return this.source.replace(BACK_REFERENCING_END, function (match, g1) {
                                return escapeRegExpCharacters(capturedValues[parseInt(g1, 10)] || "");
                            });
                        }
                    }, {
                        key: "_buildAnchorCache",
                        value: function _buildAnchorCache() {
                            if (typeof this.source !== "string") {
                                throw new Error("This method should only be called if the source is a string");
                            }
                            var A0_G0_result = [];
                            var A0_G1_result = [];
                            var A1_G0_result = [];
                            var A1_G1_result = [];
                            var pos, len, ch, nextCh;
                            for (pos = 0, len = this.source.length; pos < len; pos++) {
                                ch = this.source.charAt(pos);
                                A0_G0_result[pos] = ch;
                                A0_G1_result[pos] = ch;
                                A1_G0_result[pos] = ch;
                                A1_G1_result[pos] = ch;
                                if (ch === "\\") {
                                    if (pos + 1 < len) {
                                        nextCh = this.source.charAt(pos + 1);
                                        if (nextCh === "A") {
                                            A0_G0_result[pos + 1] = "￿";
                                            A0_G1_result[pos + 1] = "￿";
                                            A1_G0_result[pos + 1] = "A";
                                            A1_G1_result[pos + 1] = "A";
                                        } else if (nextCh === "G") {
                                            A0_G0_result[pos + 1] = "￿";
                                            A0_G1_result[pos + 1] = "G";
                                            A1_G0_result[pos + 1] = "￿";
                                            A1_G1_result[pos + 1] = "G";
                                        } else {
                                            A0_G0_result[pos + 1] = nextCh;
                                            A0_G1_result[pos + 1] = nextCh;
                                            A1_G0_result[pos + 1] = nextCh;
                                            A1_G1_result[pos + 1] = nextCh;
                                        }
                                        pos++;
                                    }
                                }
                            }
                            return {
                                A0_G0: A0_G0_result.join(""),
                                A0_G1: A0_G1_result.join(""),
                                A1_G0: A1_G0_result.join(""),
                                A1_G1: A1_G1_result.join("")
                            };
                        }
                    }, {
                        key: "resolveAnchors",
                        value: function resolveAnchors(allowA, allowG) {
                            if (!this.hasAnchor || !this._anchorCache || typeof this.source !== "string") {
                                return this.source;
                            }
                            if (allowA) {
                                if (allowG) {
                                    return this._anchorCache.A1_G1;
                                } else {
                                    return this._anchorCache.A1_G0;
                                }
                            } else {
                                if (allowG) {
                                    return this._anchorCache.A0_G1;
                                } else {
                                    return this._anchorCache.A0_G0;
                                }
                            }
                        }
                    }]);
                }();
                var RegExpSourceList = /*#__PURE__*/function () {
                    function RegExpSourceList() {
                        _classCallCheck(this, RegExpSourceList);
                        _defineProperty(this, "_items", void 0);
                        _defineProperty(this, "_hasAnchors", void 0);
                        _defineProperty(this, "_cached", void 0);
                        _defineProperty(this, "_anchorCache", void 0);
                        this._items = [];
                        this._hasAnchors = false;
                        this._cached = null;
                        this._anchorCache = {
                            A0_G0: null,
                            A0_G1: null,
                            A1_G0: null,
                            A1_G1: null
                        };
                    }

                    return _createClass(RegExpSourceList, [{
                        key: "dispose",
                        value: function dispose() {
                            this._disposeCaches();
                        }
                    }, {
                        key: "_disposeCaches",
                        value: function _disposeCaches() {
                            if (this._cached) {
                                this._cached.dispose();
                                this._cached = null;
                            }
                            if (this._anchorCache.A0_G0) {
                                this._anchorCache.A0_G0.dispose();
                                this._anchorCache.A0_G0 = null;
                            }
                            if (this._anchorCache.A0_G1) {
                                this._anchorCache.A0_G1.dispose();
                                this._anchorCache.A0_G1 = null;
                            }
                            if (this._anchorCache.A1_G0) {
                                this._anchorCache.A1_G0.dispose();
                                this._anchorCache.A1_G0 = null;
                            }
                            if (this._anchorCache.A1_G1) {
                                this._anchorCache.A1_G1.dispose();
                                this._anchorCache.A1_G1 = null;
                            }
                        }
                    }, {
                        key: "push",
                        value: function push(item) {
                            this._items.push(item);
                            this._hasAnchors = this._hasAnchors || item.hasAnchor;
                        }
                    }, {
                        key: "unshift",
                        value: function unshift(item) {
                            this._items.unshift(item);
                            this._hasAnchors = this._hasAnchors || item.hasAnchor;
                        }
                    }, {
                        key: "length",
                        value: function length() {
                            return this._items.length;
                        }
                    }, {
                        key: "setSource",
                        value: function setSource(index, newSource) {
                            if (this._items[index].source !== newSource) {
                                this._disposeCaches();
                                this._items[index].setSource(newSource);
                            }
                        }
                    }, {
                        key: "compile",
                        value: function compile(onigLib) {
                            if (!this._cached) {
                                var regExps = this._items.map(function (e) {
                                    return e.source;
                                });
                                this._cached = new CompiledRule(onigLib, regExps, this._items.map(function (e) {
                                    return e.ruleId;
                                }));
                            }
                            return this._cached;
                        }
                    }, {
                        key: "compileAG",
                        value: function compileAG(onigLib, allowA, allowG) {
                            if (!this._hasAnchors) {
                                return this.compile(onigLib);
                            } else {
                                if (allowA) {
                                    if (allowG) {
                                        if (!this._anchorCache.A1_G1) {
                                            this._anchorCache.A1_G1 = this._resolveAnchors(onigLib, allowA, allowG);
                                        }
                                        return this._anchorCache.A1_G1;
                                    } else {
                                        if (!this._anchorCache.A1_G0) {
                                            this._anchorCache.A1_G0 = this._resolveAnchors(onigLib, allowA, allowG);
                                        }
                                        return this._anchorCache.A1_G0;
                                    }
                                } else {
                                    if (allowG) {
                                        if (!this._anchorCache.A0_G1) {
                                            this._anchorCache.A0_G1 = this._resolveAnchors(onigLib, allowA, allowG);
                                        }
                                        return this._anchorCache.A0_G1;
                                    } else {
                                        if (!this._anchorCache.A0_G0) {
                                            this._anchorCache.A0_G0 = this._resolveAnchors(onigLib, allowA, allowG);
                                        }
                                        return this._anchorCache.A0_G0;
                                    }
                                }
                            }
                        }
                    }, {
                        key: "_resolveAnchors",
                        value: function _resolveAnchors(onigLib, allowA, allowG) {
                            var regExps = this._items.map(function (e) {
                                return e.resolveAnchors(allowA, allowG);
                            });
                            return new CompiledRule(onigLib, regExps, this._items.map(function (e) {
                                return e.ruleId;
                            }));
                        }
                    }]);
                }();
                var CompiledRule = /*#__PURE__*/function () {
                    function CompiledRule(onigLib, regExps, rules) {
                        _classCallCheck(this, CompiledRule);
                        _defineProperty(this, "scanner", void 0);
                        this.regExps = regExps;
                        this.rules = rules;
                        this.scanner = onigLib.createOnigScanner(regExps);
                    }

                    return _createClass(CompiledRule, [{
                        key: "dispose",
                        value: function dispose() {
                            if (typeof this.scanner.dispose === "function") {
                                this.scanner.dispose();
                            }
                        }
                    }, {
                        key: "toString",
                        value: function toString() {
                            var r = [];
                            for (var i = 0, len = this.rules.length; i < len; i++) {
                                r.push("   - " + this.rules[i] + ": " + this.regExps[i]);
                            }
                            return r.join("\n");
                        }
                    }, {
                        key: "findNextMatchSync",
                        value: function findNextMatchSync(string, startPosition, options) {
                            var result = this.scanner.findNextMatchSync(string, startPosition, options);
                            if (!result) {
                                return null;
                            }
                            return {
                                ruleId: this.rules[result.index],
                                captureIndices: result.captureIndices
                            };
                        }
                    }]);
                }();
                var BasicScopeAttributes = /*#__PURE__*/_createClass(function BasicScopeAttributes(languageId, tokenType) {
                    _classCallCheck(this, BasicScopeAttributes);
                    this.languageId = languageId;
                    this.tokenType = tokenType;
                });
                var BasicScopeAttributesProvider = (_BasicScopeAttributesProvider2 = /*#__PURE__*/function () {
                    function _BasicScopeAttributesProvider(initialLanguageId, embeddedLanguages) {
                        var _this9 = this;
                        _classCallCheck(this, _BasicScopeAttributesProvider);
                        _defineProperty(this, "_defaultAttributes", void 0);
                        _defineProperty(this, "_embeddedLanguagesMatcher", void 0);
                        _defineProperty(this, "_getBasicScopeAttributes", new CachedFn(function (scopeName) {
                            var languageId = _this9._scopeToLanguage(scopeName);
                            var standardTokenType = _this9._toStandardTokenType(scopeName);
                            return new BasicScopeAttributes(languageId, standardTokenType);
                        }));
                        this._defaultAttributes = new BasicScopeAttributes(initialLanguageId, 8
                            /* NotSet */);
                        this._embeddedLanguagesMatcher = new ScopeMatcher(Object.entries(embeddedLanguages || {}));
                    }

                    return _createClass(_BasicScopeAttributesProvider, [{
                        key: "getDefaultAttributes",
                        value: function getDefaultAttributes() {
                            return this._defaultAttributes;
                        }
                    }, {
                        key: "getBasicScopeAttributes",
                        value: function getBasicScopeAttributes(scopeName) {
                            if (scopeName === null) {
                                return _BasicScopeAttributesProvider._NULL_SCOPE_METADATA;
                            }
                            return this._getBasicScopeAttributes.get(scopeName);
                        }
                    }, {
                        key: "_scopeToLanguage",
                        value:
                            /**
                             * Given a produced TM scope, return the language that token describes or null if unknown.
                             * e.g. source.html => html, source.css.embedded.html => css, punctuation.definition.tag.html => null
                             */
                            function _scopeToLanguage(scope) {
                                return this._embeddedLanguagesMatcher.match(scope) || 0;
                            }
                    }, {
                        key: "_toStandardTokenType",
                        value: function _toStandardTokenType(scopeName) {
                            var m = scopeName.match(_BasicScopeAttributesProvider.STANDARD_TOKEN_TYPE_REGEXP);
                            if (!m) {
                                return 8;
                            }
                            switch (m[1]) {
                                case "comment":
                                    return 1;
                                case "string":
                                    return 2;
                                case "regex":
                                    return 3;
                                case "meta.embedded":
                                    return 0;
                            }
                            throw new Error("Unexpected match for standard token type!");
                        }
                    }]);
                }(), _defineProperty(_BasicScopeAttributesProvider2, "_NULL_SCOPE_METADATA", new BasicScopeAttributes(0, 0)), _defineProperty(_BasicScopeAttributesProvider2, "STANDARD_TOKEN_TYPE_REGEXP", /\b(comment|string|regex|meta\.embedded)\b/), _BasicScopeAttributesProvider2);
                var ScopeMatcher = /*#__PURE__*/function () {
                    function ScopeMatcher(values) {
                        _classCallCheck(this, ScopeMatcher);
                        _defineProperty(this, "values", void 0);
                        _defineProperty(this, "scopesRegExp", void 0);
                        if (values.length === 0) {
                            this.values = null;
                            this.scopesRegExp = null;
                        } else {
                            this.values = new Map(values);
                            var escapedScopes = values.map(function (_ref3) {
                                var _ref4 = _slicedToArray(_ref3, 2),
                                    scopeName = _ref4[0],
                                    value = _ref4[1];
                                return escapeRegExpCharacters(scopeName);
                            });
                            escapedScopes.sort();
                            escapedScopes.reverse();
                            this.scopesRegExp = new RegExp("^((".concat(escapedScopes.join(")|("), "))($|\\.)"), "");
                        }
                    }

                    return _createClass(ScopeMatcher, [{
                        key: "match",
                        value: function match(scope) {
                            if (!this.scopesRegExp) {
                                return void 0;
                            }
                            var m = scope.match(this.scopesRegExp);
                            if (!m) {
                                return void 0;
                            }
                            return this.values.get(m[1]);
                        }
                    }]);
                }();
                var TokenizeStringResult = /*#__PURE__*/_createClass(function TokenizeStringResult(stack, stoppedEarly) {
                    _classCallCheck(this, TokenizeStringResult);
                    this.stack = stack;
                    this.stoppedEarly = stoppedEarly;
                });

                function _tokenizeString(grammar, lineText, isFirstLine, linePos, stack, lineTokens, checkWhileConditions, timeLimit) {
                    var lineLength = lineText.content.length;
                    var STOP = false;
                    var anchorPosition = -1;
                    if (checkWhileConditions) {
                        var whileCheckResult = _checkWhileConditions(grammar, lineText, isFirstLine, linePos, stack, lineTokens);
                        stack = whileCheckResult.stack;
                        linePos = whileCheckResult.linePos;
                        isFirstLine = whileCheckResult.isFirstLine;
                        anchorPosition = whileCheckResult.anchorPosition;
                    }
                    var startTime = Date.now();
                    while (!STOP) {
                        if (timeLimit !== 0) {
                            var elapsedTime = Date.now() - startTime;
                            if (elapsedTime > timeLimit) {
                                return new TokenizeStringResult(stack, true);
                            }
                        }
                        scanNext();
                    }
                    return new TokenizeStringResult(stack, false);

                    function scanNext() {
                        var r = matchRuleOrInjections(grammar, lineText, isFirstLine, linePos, stack, anchorPosition);
                        if (!r) {
                            lineTokens.produce(stack, lineLength);
                            STOP = true;
                            return;
                        }
                        var captureIndices = r.captureIndices;
                        var matchedRuleId = r.matchedRuleId;
                        var hasAdvanced = captureIndices && captureIndices.length > 0 ? captureIndices[0].end > linePos : false;
                        if (matchedRuleId === endRuleId) {
                            var poppedRule = stack.getRule(grammar);
                            lineTokens.produce(stack, captureIndices[0].start);
                            stack = stack.withContentNameScopesList(stack.nameScopesList);
                            handleCaptures(grammar, lineText, isFirstLine, stack, lineTokens, poppedRule.endCaptures, captureIndices);
                            lineTokens.produce(stack, captureIndices[0].end);
                            var popped = stack;
                            stack = stack.parent;
                            anchorPosition = popped.getAnchorPos();
                            if (!hasAdvanced && popped.getEnterPos() === linePos) {
                                stack = popped;
                                lineTokens.produce(stack, lineLength);
                                STOP = true;
                                return;
                            }
                        } else {
                            var _rule = grammar.getRule(matchedRuleId);
                            lineTokens.produce(stack, captureIndices[0].start);
                            var beforePush = stack;
                            var scopeName = _rule.getName(lineText.content, captureIndices);
                            var nameScopesList = stack.contentNameScopesList.pushAttributed(scopeName, grammar);
                            stack = stack.push(matchedRuleId, linePos, anchorPosition, captureIndices[0].end === lineLength, null, nameScopesList, nameScopesList);
                            if (_rule instanceof BeginEndRule) {
                                var pushedRule = _rule;
                                handleCaptures(grammar, lineText, isFirstLine, stack, lineTokens, pushedRule.beginCaptures, captureIndices);
                                lineTokens.produce(stack, captureIndices[0].end);
                                anchorPosition = captureIndices[0].end;
                                var contentName = pushedRule.getContentName(lineText.content, captureIndices);
                                var contentNameScopesList = nameScopesList.pushAttributed(contentName, grammar);
                                stack = stack.withContentNameScopesList(contentNameScopesList);
                                if (pushedRule.endHasBackReferences) {
                                    stack = stack.withEndRule(pushedRule.getEndWithResolvedBackReferences(lineText.content, captureIndices));
                                }
                                if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) {
                                    stack = stack.pop();
                                    lineTokens.produce(stack, lineLength);
                                    STOP = true;
                                    return;
                                }
                            } else if (_rule instanceof BeginWhileRule) {
                                var _pushedRule = _rule;
                                handleCaptures(grammar, lineText, isFirstLine, stack, lineTokens, _pushedRule.beginCaptures, captureIndices);
                                lineTokens.produce(stack, captureIndices[0].end);
                                anchorPosition = captureIndices[0].end;
                                var _contentName = _pushedRule.getContentName(lineText.content, captureIndices);
                                var _contentNameScopesList = nameScopesList.pushAttributed(_contentName, grammar);
                                stack = stack.withContentNameScopesList(_contentNameScopesList);
                                if (_pushedRule.whileHasBackReferences) {
                                    stack = stack.withEndRule(_pushedRule.getWhileWithResolvedBackReferences(lineText.content, captureIndices));
                                }
                                if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) {
                                    stack = stack.pop();
                                    lineTokens.produce(stack, lineLength);
                                    STOP = true;
                                    return;
                                }
                            } else {
                                var matchingRule = _rule;
                                handleCaptures(grammar, lineText, isFirstLine, stack, lineTokens, matchingRule.captures, captureIndices);
                                lineTokens.produce(stack, captureIndices[0].end);
                                stack = stack.pop();
                                if (!hasAdvanced) {
                                    stack = stack.safePop();
                                    lineTokens.produce(stack, lineLength);
                                    STOP = true;
                                    return;
                                }
                            }
                        }
                        if (captureIndices[0].end > linePos) {
                            linePos = captureIndices[0].end;
                            isFirstLine = false;
                        }
                    }
                }

                function _checkWhileConditions(grammar, lineText, isFirstLine, linePos, stack, lineTokens) {
                    var anchorPosition = stack.beginRuleCapturedEOL ? 0 : -1;
                    var whileRules = [];
                    for (var node = stack; node; node = node.pop()) {
                        var nodeRule = node.getRule(grammar);
                        if (nodeRule instanceof BeginWhileRule) {
                            whileRules.push({
                                rule: nodeRule,
                                stack: node
                            });
                        }
                    }
                    for (var whileRule = whileRules.pop(); whileRule; whileRule = whileRules.pop()) {
                        var _prepareRuleWhileSear = prepareRuleWhileSearch(whileRule.rule, grammar, whileRule.stack.endRule, isFirstLine, linePos === anchorPosition),
                            ruleScanner = _prepareRuleWhileSear.ruleScanner,
                            findOptions = _prepareRuleWhileSear.findOptions;
                        var r = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);
                        if (r) {
                            var matchedRuleId = r.ruleId;
                            if (matchedRuleId !== whileRuleId) {
                                stack = whileRule.stack.pop();
                                break;
                            }
                            if (r.captureIndices && r.captureIndices.length) {
                                lineTokens.produce(whileRule.stack, r.captureIndices[0].start);
                                handleCaptures(grammar, lineText, isFirstLine, whileRule.stack, lineTokens, whileRule.rule.whileCaptures, r.captureIndices);
                                lineTokens.produce(whileRule.stack, r.captureIndices[0].end);
                                anchorPosition = r.captureIndices[0].end;
                                if (r.captureIndices[0].end > linePos) {
                                    linePos = r.captureIndices[0].end;
                                    isFirstLine = false;
                                }
                            }
                        } else {
                            stack = whileRule.stack.pop();
                            break;
                        }
                    }
                    return {
                        stack: stack,
                        linePos: linePos,
                        anchorPosition: anchorPosition,
                        isFirstLine: isFirstLine
                    };
                }

                function matchRuleOrInjections(grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {
                    var matchResult = matchRule(grammar, lineText, isFirstLine, linePos, stack, anchorPosition);
                    var injections = grammar.getInjections();
                    if (injections.length === 0) {
                        return matchResult;
                    }
                    var injectionResult = matchInjections(injections, grammar, lineText, isFirstLine, linePos, stack, anchorPosition);
                    if (!injectionResult) {
                        return matchResult;
                    }
                    if (!matchResult) {
                        return injectionResult;
                    }
                    var matchResultScore = matchResult.captureIndices[0].start;
                    var injectionResultScore = injectionResult.captureIndices[0].start;
                    if (injectionResultScore < matchResultScore || injectionResult.priorityMatch && injectionResultScore === matchResultScore) {
                        return injectionResult;
                    }
                    return matchResult;
                }

                function matchRule(grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {
                    var rule = stack.getRule(grammar);
                    var _prepareRuleSearch = prepareRuleSearch(rule, grammar, stack.endRule, isFirstLine, linePos === anchorPosition),
                        ruleScanner = _prepareRuleSearch.ruleScanner,
                        findOptions = _prepareRuleSearch.findOptions;
                    var r = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);
                    if (r) {
                        return {
                            captureIndices: r.captureIndices,
                            matchedRuleId: r.ruleId
                        };
                    }
                    return null;
                }

                function matchInjections(injections, grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {
                    var bestMatchRating = Number.MAX_VALUE;
                    var bestMatchCaptureIndices = null;
                    var bestMatchRuleId;
                    var bestMatchResultPriority = 0;
                    var scopes = stack.contentNameScopesList.getScopeNames();
                    for (var i = 0, len = injections.length; i < len; i++) {
                        var injection = injections[i];
                        if (!injection.matcher(scopes)) {
                            continue;
                        }
                        var rule = grammar.getRule(injection.ruleId);
                        var _prepareRuleSearch2 = prepareRuleSearch(rule, grammar, null, isFirstLine, linePos === anchorPosition),
                            ruleScanner = _prepareRuleSearch2.ruleScanner,
                            findOptions = _prepareRuleSearch2.findOptions;
                        var matchResult = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);
                        if (!matchResult) {
                            continue;
                        }
                        var matchRating = matchResult.captureIndices[0].start;
                        if (matchRating >= bestMatchRating) {
                            continue;
                        }
                        bestMatchRating = matchRating;
                        bestMatchCaptureIndices = matchResult.captureIndices;
                        bestMatchRuleId = matchResult.ruleId;
                        bestMatchResultPriority = injection.priority;
                        if (bestMatchRating === linePos) {
                            break;
                        }
                    }
                    if (bestMatchCaptureIndices) {
                        return {
                            priorityMatch: bestMatchResultPriority === -1,
                            captureIndices: bestMatchCaptureIndices,
                            matchedRuleId: bestMatchRuleId
                        };
                    }
                    return null;
                }

                function prepareRuleSearch(rule, grammar, endRegexSource, allowA, allowG) {
                    var ruleScanner = rule.compileAG(grammar, endRegexSource, allowA, allowG);
                    return {
                        ruleScanner: ruleScanner,
                        findOptions: 0
                        /* None */
                    };
                }

                function prepareRuleWhileSearch(rule, grammar, endRegexSource, allowA, allowG) {
                    var ruleScanner = rule.compileWhileAG(grammar, endRegexSource, allowA, allowG);
                    return {
                        ruleScanner: ruleScanner,
                        findOptions: 0
                        /* None */
                    };
                }

                function handleCaptures(grammar, lineText, isFirstLine, stack, lineTokens, captures, captureIndices) {
                    if (captures.length === 0) {
                        return;
                    }
                    var lineTextContent = lineText.content;
                    var len = Math.min(captures.length, captureIndices.length);
                    var localStack = [];
                    var maxEnd = captureIndices[0].end;
                    for (var i = 0; i < len; i++) {
                        var captureRule = captures[i];
                        if (captureRule === null) {
                            continue;
                        }
                        var captureIndex = captureIndices[i];
                        if (captureIndex.length === 0) {
                            continue;
                        }
                        if (captureIndex.start > maxEnd) {
                            break;
                        }
                        while (localStack.length > 0 && localStack[localStack.length - 1].endPos <= captureIndex.start) {
                            lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, localStack[localStack.length - 1].endPos);
                            localStack.pop();
                        }
                        if (localStack.length > 0) {
                            lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, captureIndex.start);
                        } else {
                            lineTokens.produce(stack, captureIndex.start);
                        }
                        if (captureRule.retokenizeCapturedWithRuleId) {
                            var scopeName = captureRule.getName(lineTextContent, captureIndices);
                            var nameScopesList = stack.contentNameScopesList.pushAttributed(scopeName, grammar);
                            var contentName = captureRule.getContentName(lineTextContent, captureIndices);
                            var contentNameScopesList = nameScopesList.pushAttributed(contentName, grammar);
                            var stackClone = stack.push(captureRule.retokenizeCapturedWithRuleId, captureIndex.start, -1, false, null, nameScopesList, contentNameScopesList);
                            var onigSubStr = grammar.createOnigString(lineTextContent.substring(0, captureIndex.end));
                            _tokenizeString(grammar, onigSubStr, isFirstLine && captureIndex.start === 0, captureIndex.start, stackClone, lineTokens, false, /* no time limit */
                                0);
                            disposeOnigString(onigSubStr);
                            continue;
                        }
                        var captureRuleScopeName = captureRule.getName(lineTextContent, captureIndices);
                        if (captureRuleScopeName !== null) {
                            var base = localStack.length > 0 ? localStack[localStack.length - 1].scopes : stack.contentNameScopesList;
                            var captureRuleScopesList = base.pushAttributed(captureRuleScopeName, grammar);
                            localStack.push(new LocalStackElement(captureRuleScopesList, captureIndex.end));
                        }
                    }
                    while (localStack.length > 0) {
                        lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, localStack[localStack.length - 1].endPos);
                        localStack.pop();
                    }
                }

                var LocalStackElement = /*#__PURE__*/_createClass(function LocalStackElement(scopes, endPos) {
                    _classCallCheck(this, LocalStackElement);
                    _defineProperty(this, "scopes", void 0);
                    _defineProperty(this, "endPos", void 0);
                    this.scopes = scopes;
                    this.endPos = endPos;
                });

                function createGrammar(scopeName, grammar, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors, grammarRepository, onigLib) {
                    return new Grammar(scopeName, grammar, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors, grammarRepository, onigLib);
                }

                function collectInjections(result, selector, rule, ruleFactoryHelper, grammar) {
                    var matchers = createMatchers(selector, nameMatcher);
                    var ruleId = RuleFactory.getCompiledRuleId(rule, ruleFactoryHelper, grammar.repository);
                    var _iterator9 = _createForOfIteratorHelper(matchers),
                        _step9;
                    try {
                        for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
                            var matcher = _step9.value;
                            result.push({
                                debugSelector: selector,
                                matcher: matcher.matcher,
                                ruleId: ruleId,
                                grammar: grammar,
                                priority: matcher.priority
                            });
                        }
                    } catch (err) {
                        _iterator9.e(err);
                    } finally {
                        _iterator9.f();
                    }
                }

                function nameMatcher(identifers, scopes) {
                    if (scopes.length < identifers.length) {
                        return false;
                    }
                    var lastIndex = 0;
                    return identifers.every(function (identifier) {
                        for (var i = lastIndex; i < scopes.length; i++) {
                            if (scopesAreMatching(scopes[i], identifier)) {
                                lastIndex = i + 1;
                                return true;
                            }
                        }
                        return false;
                    });
                }

                function scopesAreMatching(thisScopeName, scopeName) {
                    if (!thisScopeName) {
                        return false;
                    }
                    if (thisScopeName === scopeName) {
                        return true;
                    }
                    var len = scopeName.length;
                    return thisScopeName.length > len && thisScopeName.substr(0, len) === scopeName && thisScopeName[len] === ".";
                }

                var Grammar = /*#__PURE__*/function () {
                    function Grammar(_rootScopeName, grammar, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors, grammarRepository, _onigLib) {
                        _classCallCheck(this, Grammar);
                        _defineProperty(this, "_rootId", void 0);
                        _defineProperty(this, "_lastRuleId", void 0);
                        _defineProperty(this, "_ruleId2desc", void 0);
                        _defineProperty(this, "_includedGrammars", void 0);
                        _defineProperty(this, "_grammarRepository", void 0);
                        _defineProperty(this, "_grammar", void 0);
                        _defineProperty(this, "_injections", void 0);
                        _defineProperty(this, "_basicScopeAttributesProvider", void 0);
                        _defineProperty(this, "_tokenTypeMatchers", void 0);
                        this._rootScopeName = _rootScopeName;
                        this.balancedBracketSelectors = balancedBracketSelectors;
                        this._onigLib = _onigLib;
                        this._basicScopeAttributesProvider = new BasicScopeAttributesProvider(initialLanguage, embeddedLanguages);
                        this._rootId = -1;
                        this._lastRuleId = 0;
                        this._ruleId2desc = [null];
                        this._includedGrammars = {};
                        this._grammarRepository = grammarRepository;
                        this._grammar = initGrammar(grammar, null);
                        this._injections = null;
                        this._tokenTypeMatchers = [];
                        if (tokenTypes) {
                            for (var _i2 = 0, _Object$keys = Object.keys(tokenTypes); _i2 < _Object$keys.length; _i2++) {
                                var selector = _Object$keys[_i2];
                                var matchers = createMatchers(selector, nameMatcher);
                                var _iterator10 = _createForOfIteratorHelper(matchers),
                                    _step10;
                                try {
                                    for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
                                        var matcher = _step10.value;
                                        this._tokenTypeMatchers.push({
                                            matcher: matcher.matcher,
                                            type: tokenTypes[selector]
                                        });
                                    }
                                } catch (err) {
                                    _iterator10.e(err);
                                } finally {
                                    _iterator10.f();
                                }
                            }
                        }
                    }

                    return _createClass(Grammar, [{
                        key: "themeProvider",
                        get: function get() {
                            return this._grammarRepository;
                        }
                    }, {
                        key: "dispose",
                        value: function dispose() {
                            var _iterator11 = _createForOfIteratorHelper(this._ruleId2desc),
                                _step11;
                            try {
                                for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
                                    var rule = _step11.value;
                                    if (rule) {
                                        rule.dispose();
                                    }
                                }
                            } catch (err) {
                                _iterator11.e(err);
                            } finally {
                                _iterator11.f();
                            }
                        }
                    }, {
                        key: "createOnigScanner",
                        value: function createOnigScanner(sources) {
                            return this._onigLib.createOnigScanner(sources);
                        }
                    }, {
                        key: "createOnigString",
                        value: function createOnigString(sources) {
                            return this._onigLib.createOnigString(sources);
                        }
                    }, {
                        key: "getMetadataForScope",
                        value: function getMetadataForScope(scope) {
                            return this._basicScopeAttributesProvider.getBasicScopeAttributes(scope);
                        }
                    }, {
                        key: "_collectInjections",
                        value: function _collectInjections() {
                            var _this10 = this;
                            var grammarRepository = {
                                lookup: function lookup(scopeName2) {
                                    if (scopeName2 === _this10._rootScopeName) {
                                        return _this10._grammar;
                                    }
                                    return _this10.getExternalGrammar(scopeName2);
                                },
                                injections: function injections(scopeName2) {
                                    return _this10._grammarRepository.injections(scopeName2);
                                }
                            };
                            var result = [];
                            var scopeName = this._rootScopeName;
                            var grammar = grammarRepository.lookup(scopeName);
                            if (grammar) {
                                var rawInjections = grammar.injections;
                                if (rawInjections) {
                                    for (var expression in rawInjections) {
                                        collectInjections(result, expression, rawInjections[expression], this, grammar);
                                    }
                                }
                                var injectionScopeNames = this._grammarRepository.injections(scopeName);
                                if (injectionScopeNames) {
                                    injectionScopeNames.forEach(function (injectionScopeName) {
                                        var injectionGrammar = _this10.getExternalGrammar(injectionScopeName);
                                        if (injectionGrammar) {
                                            var selector = injectionGrammar.injectionSelector;
                                            if (selector) {
                                                collectInjections(result, selector, injectionGrammar, _this10, injectionGrammar);
                                            }
                                        }
                                    });
                                }
                            }
                            result.sort(function (i1, i2) {
                                return i1.priority - i2.priority;
                            });
                            return result;
                        }
                    }, {
                        key: "getInjections",
                        value: function getInjections() {
                            if (this._injections === null) {
                                this._injections = this._collectInjections();
                            }
                            return this._injections;
                        }
                    }, {
                        key: "registerRule",
                        value: function registerRule(factory) {
                            var id = ++this._lastRuleId;
                            var result = factory(ruleIdFromNumber(id));
                            this._ruleId2desc[id] = result;
                            return result;
                        }
                    }, {
                        key: "getRule",
                        value: function getRule(ruleId) {
                            return this._ruleId2desc[ruleIdToNumber(ruleId)];
                        }
                    }, {
                        key: "getExternalGrammar",
                        value: function getExternalGrammar(scopeName, repository) {
                            if (this._includedGrammars[scopeName]) {
                                return this._includedGrammars[scopeName];
                            } else if (this._grammarRepository) {
                                var rawIncludedGrammar = this._grammarRepository.lookup(scopeName);
                                if (rawIncludedGrammar) {
                                    this._includedGrammars[scopeName] = initGrammar(rawIncludedGrammar, repository && repository.$base);
                                    return this._includedGrammars[scopeName];
                                }
                            }
                            return void 0;
                        }
                    }, {
                        key: "tokenizeLine",
                        value: function tokenizeLine(lineText, prevState) {
                            var timeLimit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
                            var r = this._tokenize(lineText, prevState, false, timeLimit);
                            return {
                                tokens: r.lineTokens.getResult(r.ruleStack, r.lineLength),
                                ruleStack: r.ruleStack,
                                stoppedEarly: r.stoppedEarly
                            };
                        }
                    }, {
                        key: "tokenizeLine2",
                        value: function tokenizeLine2(lineText, prevState) {
                            var timeLimit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
                            var r = this._tokenize(lineText, prevState, true, timeLimit);
                            return {
                                tokens: r.lineTokens.getBinaryResult(r.ruleStack, r.lineLength),
                                ruleStack: r.ruleStack,
                                stoppedEarly: r.stoppedEarly
                            };
                        }
                    }, {
                        key: "_tokenize",
                        value: function _tokenize(lineText, prevState, emitBinaryTokens, timeLimit) {
                            if (this._rootId === -1) {
                                this._rootId = RuleFactory.getCompiledRuleId(this._grammar.repository.$self, this, this._grammar.repository);
                                this.getInjections();
                            }
                            var isFirstLine;
                            if (!prevState || prevState === StateStackImpl.NULL) {
                                isFirstLine = true;
                                var rawDefaultMetadata = this._basicScopeAttributesProvider.getDefaultAttributes();
                                var defaultStyle = this.themeProvider.getDefaults();
                                var defaultMetadata = EncodedTokenMetadata.set(0, rawDefaultMetadata.languageId, rawDefaultMetadata.tokenType, null, defaultStyle.fontStyle, defaultStyle.foregroundId, defaultStyle.backgroundId);
                                var rootScopeName = this.getRule(this._rootId).getName(null, null);
                                var scopeList;
                                if (rootScopeName) {
                                    scopeList = AttributedScopeStack.createRootAndLookUpScopeName(rootScopeName, defaultMetadata, this);
                                } else {
                                    scopeList = AttributedScopeStack.createRoot("unknown", defaultMetadata);
                                }
                                prevState = new StateStackImpl(null, this._rootId, -1, -1, false, null, scopeList, scopeList);
                            } else {
                                isFirstLine = false;
                                prevState.reset();
                            }
                            lineText = lineText + "\n";
                            var onigLineText = this.createOnigString(lineText);
                            var lineLength = onigLineText.content.length;
                            var lineTokens = new LineTokens(emitBinaryTokens, lineText, this._tokenTypeMatchers, this.balancedBracketSelectors);
                            var r = _tokenizeString(this, onigLineText, isFirstLine, 0, prevState, lineTokens, true, timeLimit);
                            disposeOnigString(onigLineText);
                            return {
                                lineLength: lineLength,
                                lineTokens: lineTokens,
                                ruleStack: r.stack,
                                stoppedEarly: r.stoppedEarly
                            };
                        }
                    }]);
                }();

                function initGrammar(grammar, base) {
                    grammar = clone(grammar);
                    grammar.repository = grammar.repository || {};
                    grammar.repository.$self = {
                        $vscodeTextmateLocation: grammar.$vscodeTextmateLocation,
                        patterns: grammar.patterns,
                        name: grammar.scopeName
                    };
                    grammar.repository.$base = base || grammar.repository.$self;
                    return grammar;
                }

                var AttributedScopeStack = /*#__PURE__*/function () {
                    /**
                     * Invariant:
                     * ```
                     * if (parent && !scopePath.extends(parent.scopePath)) {
                     * 	throw new Error();
                     * }
                     * ```
                     */
                    function _AttributedScopeStack(parent, scopePath, tokenAttributes) {
                        _classCallCheck(this, _AttributedScopeStack);
                        this.parent = parent;
                        this.scopePath = scopePath;
                        this.tokenAttributes = tokenAttributes;
                    }

                    return _createClass(_AttributedScopeStack, [{
                        key: "scopeName",
                        get: function get() {
                            return this.scopePath.scopeName;
                        }
                    }, {
                        key: "toString",
                        value: function toString() {
                            return this.getScopeNames().join(" ");
                        }
                    }, {
                        key: "equals",
                        value: function equals(other) {
                            return _AttributedScopeStack.equals(this, other);
                        }
                    }, {
                        key: "pushAttributed",
                        value: function pushAttributed(scopePath, grammar) {
                            if (scopePath === null) {
                                return this;
                            }
                            if (scopePath.indexOf(" ") === -1) {
                                return _AttributedScopeStack._pushAttributed(this, scopePath, grammar);
                            }
                            var scopes = scopePath.split(/ /g);
                            var result = this;
                            var _iterator12 = _createForOfIteratorHelper(scopes),
                                _step12;
                            try {
                                for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
                                    var scope = _step12.value;
                                    result = _AttributedScopeStack._pushAttributed(result, scope, grammar);
                                }
                            } catch (err) {
                                _iterator12.e(err);
                            } finally {
                                _iterator12.f();
                            }
                            return result;
                        }
                    }, {
                        key: "getScopeNames",
                        value: function getScopeNames() {
                            return this.scopePath.getSegments();
                        }
                    }, {
                        key: "getExtensionIfDefined",
                        value: function getExtensionIfDefined(base) {
                            var result = [];
                            var self = this;
                            while (self && self !== base) {
                                var _self$parent$scopePat, _self$parent;
                                result.push({
                                    encodedTokenAttributes: self.tokenAttributes,
                                    scopeNames: self.scopePath.getExtensionIfDefined((_self$parent$scopePat = (_self$parent = self.parent) === null || _self$parent === void 0 ? void 0 : _self$parent.scopePath) !== null && _self$parent$scopePat !== void 0 ? _self$parent$scopePat : null)
                                });
                                self = self.parent;
                            }
                            return self === base ? result.reverse() : void 0;
                        }
                    }], [{
                        key: "fromExtension",
                        value: function fromExtension(namesScopeList, contentNameScopesList) {
                            var _namesScopeList$scope;
                            var current = namesScopeList;
                            var scopeNames = (_namesScopeList$scope = namesScopeList === null || namesScopeList === void 0 ? void 0 : namesScopeList.scopePath) !== null && _namesScopeList$scope !== void 0 ? _namesScopeList$scope : null;
                            var _iterator13 = _createForOfIteratorHelper(contentNameScopesList),
                                _step13;
                            try {
                                for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) {
                                    var frame = _step13.value;
                                    scopeNames = ScopeStack.push(scopeNames, frame.scopeNames);
                                    current = new _AttributedScopeStack(current, scopeNames, frame.encodedTokenAttributes);
                                }
                            } catch (err) {
                                _iterator13.e(err);
                            } finally {
                                _iterator13.f();
                            }
                            return current;
                        }
                    }, {
                        key: "createRoot",
                        value: function createRoot(scopeName, tokenAttributes) {
                            return new _AttributedScopeStack(null, new ScopeStack(null, scopeName), tokenAttributes);
                        }
                    }, {
                        key: "createRootAndLookUpScopeName",
                        value: function createRootAndLookUpScopeName(scopeName, tokenAttributes, grammar) {
                            var rawRootMetadata = grammar.getMetadataForScope(scopeName);
                            var scopePath = new ScopeStack(null, scopeName);
                            var rootStyle = grammar.themeProvider.themeMatch(scopePath);
                            var resolvedTokenAttributes = _AttributedScopeStack.mergeAttributes(tokenAttributes, rawRootMetadata, rootStyle);
                            return new _AttributedScopeStack(null, scopePath, resolvedTokenAttributes);
                        }
                    }, {
                        key: "equals",
                        value: function equals(a, b) {
                            do {
                                if (a === b) {
                                    return true;
                                }
                                if (!a && !b) {
                                    return true;
                                }
                                if (!a || !b) {
                                    return false;
                                }
                                if (a.scopeName !== b.scopeName || a.tokenAttributes !== b.tokenAttributes) {
                                    return false;
                                }
                                a = a.parent;
                                b = b.parent;
                            } while (true);
                        }
                    }, {
                        key: "mergeAttributes",
                        value: function mergeAttributes(existingTokenAttributes, basicScopeAttributes, styleAttributes) {
                            var fontStyle = -1;
                            var foreground = 0;
                            var background = 0;
                            if (styleAttributes !== null) {
                                fontStyle = styleAttributes.fontStyle;
                                foreground = styleAttributes.foregroundId;
                                background = styleAttributes.backgroundId;
                            }
                            return EncodedTokenMetadata.set(existingTokenAttributes, basicScopeAttributes.languageId, basicScopeAttributes.tokenType, null, fontStyle, foreground, background);
                        }
                    }, {
                        key: "_pushAttributed",
                        value: function _pushAttributed(target, scopeName, grammar) {
                            var rawMetadata = grammar.getMetadataForScope(scopeName);
                            var newPath = target.scopePath.push(scopeName);
                            var scopeThemeMatchResult = grammar.themeProvider.themeMatch(newPath);
                            var metadata = _AttributedScopeStack.mergeAttributes(target.tokenAttributes, rawMetadata, scopeThemeMatchResult);
                            return new _AttributedScopeStack(target, newPath, metadata);
                        }
                    }]);
                }();
                var StateStackImpl = (_StateStackImpl2 = /*#__PURE__*/function () {
                    /**
                     * Invariant:
                     * ```
                     * if (contentNameScopesList !== nameScopesList && contentNameScopesList?.parent !== nameScopesList) {
                     * 	throw new Error();
                     * }
                     * if (this.parent && !nameScopesList.extends(this.parent.contentNameScopesList)) {
                     * 	throw new Error();
                     * }
                     * ```
                     */
                    function _StateStackImpl(parent, ruleId, enterPos, anchorPos, beginRuleCapturedEOL, endRule, nameScopesList, contentNameScopesList) {
                        _classCallCheck(this, _StateStackImpl);
                        _defineProperty(this, "_stackElementBrand", void 0);
                        /**
                         * The position on the current line where this state was pushed.
                         * This is relevant only while tokenizing a line, to detect endless loops.
                         * Its value is meaningless across lines.
                         */
                        _defineProperty(this, "_enterPos", void 0);
                        /**
                         * The captured anchor position when this stack element was pushed.
                         * This is relevant only while tokenizing a line, to restore the anchor position when popping.
                         * Its value is meaningless across lines.
                         */
                        _defineProperty(this, "_anchorPos", void 0);
                        /**
                         * The depth of the stack.
                         */
                        _defineProperty(this, "depth", void 0);
                        this.parent = parent;
                        this.ruleId = ruleId;
                        this.beginRuleCapturedEOL = beginRuleCapturedEOL;
                        this.endRule = endRule;
                        this.nameScopesList = nameScopesList;
                        this.contentNameScopesList = contentNameScopesList;
                        this.depth = this.parent ? this.parent.depth + 1 : 1;
                        this._enterPos = enterPos;
                        this._anchorPos = anchorPos;
                    }

                    return _createClass(_StateStackImpl, [{
                        key: "equals",
                        value: function equals(other) {
                            if (other === null) {
                                return false;
                            }
                            return _StateStackImpl._equals(this, other);
                        }
                    }, {
                        key: "clone",
                        value: function clone() {
                            return this;
                        }
                    }, {
                        key: "reset",
                        value: function reset() {
                            _StateStackImpl._reset(this);
                        }
                    }, {
                        key: "pop",
                        value: function pop() {
                            return this.parent;
                        }
                    }, {
                        key: "safePop",
                        value: function safePop() {
                            if (this.parent) {
                                return this.parent;
                            }
                            return this;
                        }
                    }, {
                        key: "push",
                        value: function push(ruleId, enterPos, anchorPos, beginRuleCapturedEOL, endRule, nameScopesList, contentNameScopesList) {
                            return new _StateStackImpl(this, ruleId, enterPos, anchorPos, beginRuleCapturedEOL, endRule, nameScopesList, contentNameScopesList);
                        }
                    }, {
                        key: "getEnterPos",
                        value: function getEnterPos() {
                            return this._enterPos;
                        }
                    }, {
                        key: "getAnchorPos",
                        value: function getAnchorPos() {
                            return this._anchorPos;
                        }
                    }, {
                        key: "getRule",
                        value: function getRule(grammar) {
                            return grammar.getRule(this.ruleId);
                        }
                    }, {
                        key: "toString",
                        value: function toString() {
                            var r = [];
                            this._writeString(r, 0);
                            return "[" + r.join(",") + "]";
                        }
                    }, {
                        key: "_writeString",
                        value: function _writeString(res, outIndex) {
                            var _this$nameScopesList, _this$contentNameScop;
                            if (this.parent) {
                                outIndex = this.parent._writeString(res, outIndex);
                            }
                            res[outIndex++] = "(".concat(this.ruleId, ", ").concat((_this$nameScopesList = this.nameScopesList) === null || _this$nameScopesList === void 0 ? void 0 : _this$nameScopesList.toString(), ", ").concat((_this$contentNameScop = this.contentNameScopesList) === null || _this$contentNameScop === void 0 ? void 0 : _this$contentNameScop.toString(), ")");
                            return outIndex;
                        }
                    }, {
                        key: "withContentNameScopesList",
                        value: function withContentNameScopesList(contentNameScopeStack) {
                            if (this.contentNameScopesList === contentNameScopeStack) {
                                return this;
                            }
                            return this.parent.push(this.ruleId, this._enterPos, this._anchorPos, this.beginRuleCapturedEOL, this.endRule, this.nameScopesList, contentNameScopeStack);
                        }
                    }, {
                        key: "withEndRule",
                        value: function withEndRule(endRule) {
                            if (this.endRule === endRule) {
                                return this;
                            }
                            return new _StateStackImpl(this.parent, this.ruleId, this._enterPos, this._anchorPos, this.beginRuleCapturedEOL, endRule, this.nameScopesList, this.contentNameScopesList);
                        }
                        // Used to warn of endless loops
                    }, {
                        key: "hasSameRuleAs",
                        value: function hasSameRuleAs(other) {
                            var el = this;
                            while (el && el._enterPos === other._enterPos) {
                                if (el.ruleId === other.ruleId) {
                                    return true;
                                }
                                el = el.parent;
                            }
                            return false;
                        }
                    }, {
                        key: "toStateStackFrame",
                        value: function toStateStackFrame() {
                            var _this$nameScopesList$, _this$nameScopesList2, _this$parent$nameScop, _this$parent,
                                _this$contentNameScop2, _this$contentNameScop3;
                            return {
                                ruleId: ruleIdToNumber(this.ruleId),
                                beginRuleCapturedEOL: this.beginRuleCapturedEOL,
                                endRule: this.endRule,
                                nameScopesList: (_this$nameScopesList$ = (_this$nameScopesList2 = this.nameScopesList) === null || _this$nameScopesList2 === void 0 ? void 0 : _this$nameScopesList2.getExtensionIfDefined((_this$parent$nameScop = (_this$parent = this.parent) === null || _this$parent === void 0 ? void 0 : _this$parent.nameScopesList) !== null && _this$parent$nameScop !== void 0 ? _this$parent$nameScop : null)) !== null && _this$nameScopesList$ !== void 0 ? _this$nameScopesList$ : [],
                                contentNameScopesList: (_this$contentNameScop2 = (_this$contentNameScop3 = this.contentNameScopesList) === null || _this$contentNameScop3 === void 0 ? void 0 : _this$contentNameScop3.getExtensionIfDefined(this.nameScopesList)) !== null && _this$contentNameScop2 !== void 0 ? _this$contentNameScop2 : []
                            };
                        }
                    }], [{
                        key: "_equals",
                        value: function _equals(a, b) {
                            if (a === b) {
                                return true;
                            }
                            if (!this._structuralEquals(a, b)) {
                                return false;
                            }
                            return AttributedScopeStack.equals(a.contentNameScopesList, b.contentNameScopesList);
                        }
                        /**
                         * A structural equals check. Does not take into account `scopes`.
                         */
                    }, {
                        key: "_structuralEquals",
                        value: function _structuralEquals(a, b) {
                            do {
                                if (a === b) {
                                    return true;
                                }
                                if (!a && !b) {
                                    return true;
                                }
                                if (!a || !b) {
                                    return false;
                                }
                                if (a.depth !== b.depth || a.ruleId !== b.ruleId || a.endRule !== b.endRule) {
                                    return false;
                                }
                                a = a.parent;
                                b = b.parent;
                            } while (true);
                        }
                    }, {
                        key: "_reset",
                        value: function _reset(el) {
                            while (el) {
                                el._enterPos = -1;
                                el._anchorPos = -1;
                                el = el.parent;
                            }
                        }
                    }, {
                        key: "pushFrame",
                        value: function pushFrame(self, frame) {
                            var _self$nameScopesList, _frame$enterPos, _frame$anchorPos;
                            var namesScopeList = AttributedScopeStack.fromExtension((_self$nameScopesList = self === null || self === void 0 ? void 0 : self.nameScopesList) !== null && _self$nameScopesList !== void 0 ? _self$nameScopesList : null, frame.nameScopesList);
                            return new _StateStackImpl(self, ruleIdFromNumber(frame.ruleId), (_frame$enterPos = frame.enterPos) !== null && _frame$enterPos !== void 0 ? _frame$enterPos : -1, (_frame$anchorPos = frame.anchorPos) !== null && _frame$anchorPos !== void 0 ? _frame$anchorPos : -1, frame.beginRuleCapturedEOL, frame.endRule, namesScopeList, AttributedScopeStack.fromExtension(namesScopeList, frame.contentNameScopesList));
                        }
                    }]);
                }(), _defineProperty(_StateStackImpl2, "NULL", new _StateStackImpl2(null, 0, 0, 0, false, null, null, null)), _StateStackImpl2);
                var BalancedBracketSelectors = /*#__PURE__*/function () {
                    function BalancedBracketSelectors(balancedBracketScopes, unbalancedBracketScopes) {
                        var _this11 = this;
                        _classCallCheck(this, BalancedBracketSelectors);
                        _defineProperty(this, "balancedBracketScopes", void 0);
                        _defineProperty(this, "unbalancedBracketScopes", void 0);
                        _defineProperty(this, "allowAny", false);
                        this.balancedBracketScopes = balancedBracketScopes.flatMap(function (selector) {
                            if (selector === "*") {
                                _this11.allowAny = true;
                                return [];
                            }
                            return createMatchers(selector, nameMatcher).map(function (m) {
                                return m.matcher;
                            });
                        });
                        this.unbalancedBracketScopes = unbalancedBracketScopes.flatMap(function (selector) {
                            return createMatchers(selector, nameMatcher).map(function (m) {
                                return m.matcher;
                            });
                        });
                    }

                    return _createClass(BalancedBracketSelectors, [{
                        key: "matchesAlways",
                        get: function get() {
                            return this.allowAny && this.unbalancedBracketScopes.length === 0;
                        }
                    }, {
                        key: "matchesNever",
                        get: function get() {
                            return this.balancedBracketScopes.length === 0 && !this.allowAny;
                        }
                    }, {
                        key: "match",
                        value: function match(scopes) {
                            var _iterator14 = _createForOfIteratorHelper(this.unbalancedBracketScopes),
                                _step14;
                            try {
                                for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) {
                                    var excluder = _step14.value;
                                    if (excluder(scopes)) {
                                        return false;
                                    }
                                }
                            } catch (err) {
                                _iterator14.e(err);
                            } finally {
                                _iterator14.f();
                            }
                            var _iterator15 = _createForOfIteratorHelper(this.balancedBracketScopes),
                                _step15;
                            try {
                                for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) {
                                    var includer = _step15.value;
                                    if (includer(scopes)) {
                                        return true;
                                    }
                                }
                            } catch (err) {
                                _iterator15.e(err);
                            } finally {
                                _iterator15.f();
                            }
                            return this.allowAny;
                        }
                    }]);
                }();
                var LineTokens = /*#__PURE__*/function () {
                    function LineTokens(emitBinaryTokens, lineText, tokenTypeOverrides, balancedBracketSelectors) {
                        _classCallCheck(this, LineTokens);
                        _defineProperty(this, "_emitBinaryTokens", void 0);
                        /**
                         * defined only if `false`.
                         */
                        _defineProperty(this, "_lineText", void 0);
                        /**
                         * used only if `_emitBinaryTokens` is false.
                         */
                        _defineProperty(this, "_tokens", void 0);
                        /**
                         * used only if `_emitBinaryTokens` is true.
                         */
                        _defineProperty(this, "_binaryTokens", void 0);
                        _defineProperty(this, "_lastTokenEndIndex", void 0);
                        _defineProperty(this, "_tokenTypeOverrides", void 0);
                        this.balancedBracketSelectors = balancedBracketSelectors;
                        this._emitBinaryTokens = emitBinaryTokens;
                        this._tokenTypeOverrides = tokenTypeOverrides;
                        {
                            this._lineText = null;
                        }
                        this._tokens = [];
                        this._binaryTokens = [];
                        this._lastTokenEndIndex = 0;
                    }

                    return _createClass(LineTokens, [{
                        key: "produce",
                        value: function produce(stack, endIndex) {
                            this.produceFromScopes(stack.contentNameScopesList, endIndex);
                        }
                    }, {
                        key: "produceFromScopes",
                        value: function produceFromScopes(scopesList, endIndex) {
                            var _scopesList$getScopeN2;
                            if (this._lastTokenEndIndex >= endIndex) {
                                return;
                            }
                            if (this._emitBinaryTokens) {
                                var _scopesList$tokenAttr, _this$balancedBracket;
                                var metadata = (_scopesList$tokenAttr = scopesList === null || scopesList === void 0 ? void 0 : scopesList.tokenAttributes) !== null && _scopesList$tokenAttr !== void 0 ? _scopesList$tokenAttr : 0;
                                var containsBalancedBrackets = false;
                                if ((_this$balancedBracket = this.balancedBracketSelectors) !== null && _this$balancedBracket !== void 0 && _this$balancedBracket.matchesAlways) {
                                    containsBalancedBrackets = true;
                                }
                                if (this._tokenTypeOverrides.length > 0 || this.balancedBracketSelectors && !this.balancedBracketSelectors.matchesAlways && !this.balancedBracketSelectors.matchesNever) {
                                    var _scopesList$getScopeN;
                                    var scopes2 = (_scopesList$getScopeN = scopesList === null || scopesList === void 0 ? void 0 : scopesList.getScopeNames()) !== null && _scopesList$getScopeN !== void 0 ? _scopesList$getScopeN : [];
                                    var _iterator16 = _createForOfIteratorHelper(this._tokenTypeOverrides),
                                        _step16;
                                    try {
                                        for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) {
                                            var tokenType = _step16.value;
                                            if (tokenType.matcher(scopes2)) {
                                                metadata = EncodedTokenMetadata.set(metadata, 0, toOptionalTokenType(tokenType.type), null, -1, 0, 0);
                                            }
                                        }
                                    } catch (err) {
                                        _iterator16.e(err);
                                    } finally {
                                        _iterator16.f();
                                    }
                                    if (this.balancedBracketSelectors) {
                                        containsBalancedBrackets = this.balancedBracketSelectors.match(scopes2);
                                    }
                                }
                                if (containsBalancedBrackets) {
                                    metadata = EncodedTokenMetadata.set(metadata, 0, 8, containsBalancedBrackets, -1, 0, 0);
                                }
                                if (this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 1] === metadata) {
                                    this._lastTokenEndIndex = endIndex;
                                    return;
                                }
                                this._binaryTokens.push(this._lastTokenEndIndex);
                                this._binaryTokens.push(metadata);
                                this._lastTokenEndIndex = endIndex;
                                return;
                            }
                            var scopes = (_scopesList$getScopeN2 = scopesList === null || scopesList === void 0 ? void 0 : scopesList.getScopeNames()) !== null && _scopesList$getScopeN2 !== void 0 ? _scopesList$getScopeN2 : [];
                            this._tokens.push({
                                startIndex: this._lastTokenEndIndex,
                                endIndex: endIndex,
                                // value: lineText.substring(lastTokenEndIndex, endIndex),
                                scopes: scopes
                            });
                            this._lastTokenEndIndex = endIndex;
                        }
                    }, {
                        key: "getResult",
                        value: function getResult(stack, lineLength) {
                            if (this._tokens.length > 0 && this._tokens[this._tokens.length - 1].startIndex === lineLength - 1) {
                                this._tokens.pop();
                            }
                            if (this._tokens.length === 0) {
                                this._lastTokenEndIndex = -1;
                                this.produce(stack, lineLength);
                                this._tokens[this._tokens.length - 1].startIndex = 0;
                            }
                            return this._tokens;
                        }
                    }, {
                        key: "getBinaryResult",
                        value: function getBinaryResult(stack, lineLength) {
                            if (this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 2] === lineLength - 1) {
                                this._binaryTokens.pop();
                                this._binaryTokens.pop();
                            }
                            if (this._binaryTokens.length === 0) {
                                this._lastTokenEndIndex = -1;
                                this.produce(stack, lineLength);
                                this._binaryTokens[this._binaryTokens.length - 2] = 0;
                            }
                            var result = new Uint32Array(this._binaryTokens.length);
                            for (var i = 0, len = this._binaryTokens.length; i < len; i++) {
                                result[i] = this._binaryTokens[i];
                            }
                            return result;
                        }
                    }]);
                }();
                var SyncRegistry = /*#__PURE__*/function () {
                    function SyncRegistry(theme, _onigLib) {
                        _classCallCheck(this, SyncRegistry);
                        _defineProperty(this, "_grammars", /* @__PURE__ */new Map());
                        _defineProperty(this, "_rawGrammars", /* @__PURE__ */new Map());
                        _defineProperty(this, "_injectionGrammars", /* @__PURE__ */new Map());
                        _defineProperty(this, "_theme", void 0);
                        this._onigLib = _onigLib;
                        this._theme = theme;
                    }

                    return _createClass(SyncRegistry, [{
                        key: "dispose",
                        value: function dispose() {
                            var _iterator17 = _createForOfIteratorHelper(this._grammars.values()),
                                _step17;
                            try {
                                for (_iterator17.s(); !(_step17 = _iterator17.n()).done;) {
                                    var grammar = _step17.value;
                                    grammar.dispose();
                                }
                            } catch (err) {
                                _iterator17.e(err);
                            } finally {
                                _iterator17.f();
                            }
                        }
                    }, {
                        key: "setTheme",
                        value: function setTheme(theme) {
                            this._theme = theme;
                        }
                    }, {
                        key: "getColorMap",
                        value: function getColorMap() {
                            return this._theme.getColorMap();
                        }
                        /**
                         * Add `grammar` to registry and return a list of referenced scope names
                         */
                    }, {
                        key: "addGrammar",
                        value: function addGrammar(grammar, injectionScopeNames) {
                            this._rawGrammars.set(grammar.scopeName, grammar);
                            if (injectionScopeNames) {
                                this._injectionGrammars.set(grammar.scopeName, injectionScopeNames);
                            }
                        }
                        /**
                         * Lookup a raw grammar.
                         */
                    }, {
                        key: "lookup",
                        value: function lookup(scopeName) {
                            return this._rawGrammars.get(scopeName);
                        }
                        /**
                         * Returns the injections for the given grammar
                         */
                    }, {
                        key: "injections",
                        value: function injections(targetScope) {
                            return this._injectionGrammars.get(targetScope);
                        }
                        /**
                         * Get the default theme settings
                         */
                    }, {
                        key: "getDefaults",
                        value: function getDefaults() {
                            return this._theme.getDefaults();
                        }
                        /**
                         * Match a scope in the theme.
                         */
                    }, {
                        key: "themeMatch",
                        value: function themeMatch(scopePath) {
                            return this._theme.match(scopePath);
                        }
                        /**
                         * Lookup a grammar.
                         */
                    }, {
                        key: "grammarForScopeName",
                        value: function grammarForScopeName(scopeName, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors) {
                            if (!this._grammars.has(scopeName)) {
                                var rawGrammar = this._rawGrammars.get(scopeName);
                                if (!rawGrammar) {
                                    return null;
                                }
                                this._grammars.set(scopeName, createGrammar(scopeName, rawGrammar, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors, this, this._onigLib));
                            }
                            return this._grammars.get(scopeName);
                        }
                    }]);
                }();
                var Registry$1 = /*#__PURE__*/function () {
                    function Registry(options) {
                        _classCallCheck(this, Registry);
                        _defineProperty(this, "_options", void 0);
                        _defineProperty(this, "_syncRegistry", void 0);
                        _defineProperty(this, "_ensureGrammarCache", void 0);
                        this._options = options;
                        this._syncRegistry = new SyncRegistry(Theme.createFromRawTheme(options.theme, options.colorMap), options.onigLib);
                        this._ensureGrammarCache = /* @__PURE__ */new Map();
                    }

                    return _createClass(Registry, [{
                        key: "dispose",
                        value: function dispose() {
                            this._syncRegistry.dispose();
                        }
                        /**
                         * Change the theme. Once called, no previous `ruleStack` should be used anymore.
                         */
                    }, {
                        key: "setTheme",
                        value: function setTheme(theme, colorMap) {
                            this._syncRegistry.setTheme(Theme.createFromRawTheme(theme, colorMap));
                        }
                        /**
                         * Returns a lookup array for color ids.
                         */
                    }, {
                        key: "getColorMap",
                        value: function getColorMap() {
                            return this._syncRegistry.getColorMap();
                        }
                        /**
                         * Load the grammar for `scopeName` and all referenced included grammars asynchronously.
                         * Please do not use language id 0.
                         */
                    }, {
                        key: "loadGrammarWithEmbeddedLanguages",
                        value: function loadGrammarWithEmbeddedLanguages(initialScopeName, initialLanguage, embeddedLanguages) {
                            return this.loadGrammarWithConfiguration(initialScopeName, initialLanguage, {
                                embeddedLanguages: embeddedLanguages
                            });
                        }
                        /**
                         * Load the grammar for `scopeName` and all referenced included grammars asynchronously.
                         * Please do not use language id 0.
                         */
                    }, {
                        key: "loadGrammarWithConfiguration",
                        value: function loadGrammarWithConfiguration(initialScopeName, initialLanguage, configuration) {
                            return this._loadGrammar(initialScopeName, initialLanguage, configuration.embeddedLanguages, configuration.tokenTypes, new BalancedBracketSelectors(configuration.balancedBracketSelectors || [], configuration.unbalancedBracketSelectors || []));
                        }
                        /**
                         * Load the grammar for `scopeName` and all referenced included grammars asynchronously.
                         */
                    }, {
                        key: "loadGrammar",
                        value: function loadGrammar(initialScopeName) {
                            return this._loadGrammar(initialScopeName, 0, null, null, null);
                        }
                    }, {
                        key: "_loadGrammar",
                        value: function _loadGrammar(initialScopeName, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors) {
                            var _this12 = this;
                            var dependencyProcessor = new ScopeDependencyProcessor(this._syncRegistry, initialScopeName);
                            while (dependencyProcessor.Q.length > 0) {
                                dependencyProcessor.Q.map(function (request) {
                                    return _this12._loadSingleGrammar(request.scopeName);
                                });
                                dependencyProcessor.processQueue();
                            }
                            return this._grammarForScopeName(initialScopeName, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors);
                        }
                    }, {
                        key: "_loadSingleGrammar",
                        value: function _loadSingleGrammar(scopeName) {
                            if (!this._ensureGrammarCache.has(scopeName)) {
                                this._doLoadSingleGrammar(scopeName);
                                this._ensureGrammarCache.set(scopeName, true);
                            }
                        }
                    }, {
                        key: "_doLoadSingleGrammar",
                        value: function _doLoadSingleGrammar(scopeName) {
                            var grammar = this._options.loadGrammar(scopeName);
                            if (grammar) {
                                var injections = typeof this._options.getInjections === "function" ? this._options.getInjections(scopeName) : void 0;
                                this._syncRegistry.addGrammar(grammar, injections);
                            }
                        }
                        /**
                         * Adds a rawGrammar.
                         */
                    }, {
                        key: "addGrammar",
                        value: function addGrammar(rawGrammar) {
                            var injections = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
                            var initialLanguage = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
                            var embeddedLanguages = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
                            this._syncRegistry.addGrammar(rawGrammar, injections);
                            return this._grammarForScopeName(rawGrammar.scopeName, initialLanguage, embeddedLanguages);
                        }
                        /**
                         * Get the grammar for `scopeName`. The grammar must first be created via `loadGrammar` or `addGrammar`.
                         */
                    }, {
                        key: "_grammarForScopeName",
                        value: function _grammarForScopeName(scopeName) {
                            var initialLanguage = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
                            var embeddedLanguages = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
                            var tokenTypes = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
                            var balancedBracketSelectors = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
                            return this._syncRegistry.grammarForScopeName(scopeName, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors);
                        }
                    }]);
                }();
                var INITIAL = StateStackImpl.NULL;

                /**
                 * List of HTML void tag names.
                 *
                 * @type {Array<string>}
                 */
                var htmlVoidElements = ['area', 'base', 'basefont', 'bgsound', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'image', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'];

                /**
                 * @typedef {import('./info.js').Info} Info
                 * @typedef {Record<string, Info>} Properties
                 * @typedef {Record<string, string>} Normal
                 */
                var Schema = /*#__PURE__*/_createClass(
                    /**
                     * @constructor
                     * @param {Properties} property
                     * @param {Normal} normal
                     * @param {string} [space]
                     */
                    function Schema(property, normal, space) {
                        _classCallCheck(this, Schema);
                        this.property = property;
                        this.normal = normal;
                        if (space) {
                            this.space = space;
                        }
                    });
                /** @type {Properties} */
                Schema.prototype.property = {};
                /** @type {Normal} */
                Schema.prototype.normal = {};
                /** @type {string|null} */
                Schema.prototype.space = null;

                /**
                 * @typedef {import('./schema.js').Properties} Properties
                 * @typedef {import('./schema.js').Normal} Normal
                 */

                /**
                 * @param {Schema[]} definitions
                 * @param {string} [space]
                 * @returns {Schema}
                 */
                function merge(definitions, space) {
                    /** @type {Properties} */
                    var property = {};
                    /** @type {Normal} */
                    var normal = {};
                    var index = -1;
                    while (++index < definitions.length) {
                        Object.assign(property, definitions[index].property);
                        Object.assign(normal, definitions[index].normal);
                    }
                    return new Schema(property, normal, space);
                }

                /**
                 * @param {string} value
                 * @returns {string}
                 */
                function normalize(value) {
                    return value.toLowerCase();
                }

                var Info = /*#__PURE__*/_createClass(
                    /**
                     * @constructor
                     * @param {string} property
                     * @param {string} attribute
                     */
                    function Info(property, attribute) {
                        _classCallCheck(this, Info);
                        /** @type {string} */
                        this.property = property;
                        /** @type {string} */
                        this.attribute = attribute;
                    });
                /** @type {string|null} */
                Info.prototype.space = null;
                Info.prototype.boolean = false;
                Info.prototype.booleanish = false;
                Info.prototype.overloadedBoolean = false;
                Info.prototype.number = false;
                Info.prototype.commaSeparated = false;
                Info.prototype.spaceSeparated = false;
                Info.prototype.commaOrSpaceSeparated = false;
                Info.prototype.mustUseProperty = false;
                Info.prototype.defined = false;
                var powers = 0;
                var boolean = increment();
                var booleanish = increment();
                var overloadedBoolean = increment();
                var number = increment();
                var spaceSeparated = increment();
                var commaSeparated = increment();
                var commaOrSpaceSeparated = increment();

                function increment() {
                    return Math.pow(2, ++powers);
                }

                var types = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
                    __proto__: null,
                    boolean: boolean,
                    booleanish: booleanish,
                    commaOrSpaceSeparated: commaOrSpaceSeparated,
                    commaSeparated: commaSeparated,
                    number: number,
                    overloadedBoolean: overloadedBoolean,
                    spaceSeparated: spaceSeparated
                }, Symbol.toStringTag, {
                    value: 'Module'
                }));

                /** @type {Array<keyof types>} */
                    // @ts-expect-error: hush.
                var checks = Object.keys(types);
                var DefinedInfo = /*#__PURE__*/function (_Info) {
                    /**
                     * @constructor
                     * @param {string} property
                     * @param {string} attribute
                     * @param {number|null} [mask]
                     * @param {string} [space]
                     */
                    function DefinedInfo(property, attribute, mask, space) {
                        var _this13;
                        _classCallCheck(this, DefinedInfo);
                        var index = -1;
                        _this13 = _callSuper(this, DefinedInfo, [property, attribute]);
                        mark(_this13, 'space', space);
                        if (typeof mask === 'number') {
                            while (++index < checks.length) {
                                var check = checks[index];
                                mark(_this13, checks[index], (mask & types[check]) === types[check]);
                            }
                        }
                        return _this13;
                    }

                    _inherits(DefinedInfo, _Info);
                    return _createClass(DefinedInfo);
                }(Info);
                DefinedInfo.prototype.defined = true;

                /**
                 * @param {DefinedInfo} values
                 * @param {string} key
                 * @param {unknown} value
                 */
                function mark(values, key, value) {
                    if (value) {
                        // @ts-expect-error: assume `value` matches the expected value of `key`.
                        values[key] = value;
                    }
                }

                /**
                 * @typedef {import('./schema.js').Properties} Properties
                 * @typedef {import('./schema.js').Normal} Normal
                 *
                 * @typedef {Record<string, string>} Attributes
                 *
                 * @typedef {Object} Definition
                 * @property {Record<string, number|null>} properties
                 * @property {(attributes: Attributes, property: string) => string} transform
                 * @property {string} [space]
                 * @property {Attributes} [attributes]
                 * @property {Array<string>} [mustUseProperty]
                 */

                var own$3 = {}.hasOwnProperty;

                /**
                 * @param {Definition} definition
                 * @returns {Schema}
                 */
                function create(definition) {
                    /** @type {Properties} */
                    var property = {};
                    /** @type {Normal} */
                    var normal = {};
                    /** @type {string} */
                    var prop;
                    for (prop in definition.properties) {
                        if (own$3.call(definition.properties, prop)) {
                            var value = definition.properties[prop];
                            var info = new DefinedInfo(prop, definition.transform(definition.attributes || {}, prop), value, definition.space);
                            if (definition.mustUseProperty && definition.mustUseProperty.includes(prop)) {
                                info.mustUseProperty = true;
                            }
                            property[prop] = info;
                            normal[normalize(prop)] = prop;
                            normal[normalize(info.attribute)] = prop;
                        }
                    }
                    return new Schema(property, normal, definition.space);
                }

                var xlink = create({
                    space: 'xlink',
                    transform: function transform(_, prop) {
                        return 'xlink:' + prop.slice(5).toLowerCase();
                    },
                    properties: {
                        xLinkActuate: null,
                        xLinkArcRole: null,
                        xLinkHref: null,
                        xLinkRole: null,
                        xLinkShow: null,
                        xLinkTitle: null,
                        xLinkType: null
                    }
                });
                var xml = create({
                    space: 'xml',
                    transform: function transform(_, prop) {
                        return 'xml:' + prop.slice(3).toLowerCase();
                    },
                    properties: {
                        xmlLang: null,
                        xmlBase: null,
                        xmlSpace: null
                    }
                });

                /**
                 * @param {Record<string, string>} attributes
                 * @param {string} attribute
                 * @returns {string}
                 */
                function caseSensitiveTransform(attributes, attribute) {
                    return attribute in attributes ? attributes[attribute] : attribute;
                }

                /**
                 * @param {Record<string, string>} attributes
                 * @param {string} property
                 * @returns {string}
                 */
                function caseInsensitiveTransform(attributes, property) {
                    return caseSensitiveTransform(attributes, property.toLowerCase());
                }

                var xmlns = create({
                    space: 'xmlns',
                    attributes: {
                        xmlnsxlink: 'xmlns:xlink'
                    },
                    transform: caseInsensitiveTransform,
                    properties: {
                        xmlns: null,
                        xmlnsXLink: null
                    }
                });
                var aria = create({
                    transform: function transform(_, prop) {
                        return prop === 'role' ? prop : 'aria-' + prop.slice(4).toLowerCase();
                    },
                    properties: {
                        ariaActiveDescendant: null,
                        ariaAtomic: booleanish,
                        ariaAutoComplete: null,
                        ariaBusy: booleanish,
                        ariaChecked: booleanish,
                        ariaColCount: number,
                        ariaColIndex: number,
                        ariaColSpan: number,
                        ariaControls: spaceSeparated,
                        ariaCurrent: null,
                        ariaDescribedBy: spaceSeparated,
                        ariaDetails: null,
                        ariaDisabled: booleanish,
                        ariaDropEffect: spaceSeparated,
                        ariaErrorMessage: null,
                        ariaExpanded: booleanish,
                        ariaFlowTo: spaceSeparated,
                        ariaGrabbed: booleanish,
                        ariaHasPopup: null,
                        ariaHidden: booleanish,
                        ariaInvalid: null,
                        ariaKeyShortcuts: null,
                        ariaLabel: null,
                        ariaLabelledBy: spaceSeparated,
                        ariaLevel: number,
                        ariaLive: null,
                        ariaModal: booleanish,
                        ariaMultiLine: booleanish,
                        ariaMultiSelectable: booleanish,
                        ariaOrientation: null,
                        ariaOwns: spaceSeparated,
                        ariaPlaceholder: null,
                        ariaPosInSet: number,
                        ariaPressed: booleanish,
                        ariaReadOnly: booleanish,
                        ariaRelevant: null,
                        ariaRequired: booleanish,
                        ariaRoleDescription: spaceSeparated,
                        ariaRowCount: number,
                        ariaRowIndex: number,
                        ariaRowSpan: number,
                        ariaSelected: booleanish,
                        ariaSetSize: number,
                        ariaSort: null,
                        ariaValueMax: number,
                        ariaValueMin: number,
                        ariaValueNow: number,
                        ariaValueText: null,
                        role: null
                    }
                });
                var html$3 = create({
                    space: 'html',
                    attributes: {
                        acceptcharset: 'accept-charset',
                        classname: 'class',
                        htmlfor: 'for',
                        httpequiv: 'http-equiv'
                    },
                    transform: caseInsensitiveTransform,
                    mustUseProperty: ['checked', 'multiple', 'muted', 'selected'],
                    properties: {
                        // Standard Properties.
                        abbr: null,
                        accept: commaSeparated,
                        acceptCharset: spaceSeparated,
                        accessKey: spaceSeparated,
                        action: null,
                        allow: null,
                        allowFullScreen: boolean,
                        allowPaymentRequest: boolean,
                        allowUserMedia: boolean,
                        alt: null,
                        as: null,
                        async: boolean,
                        autoCapitalize: null,
                        autoComplete: spaceSeparated,
                        autoFocus: boolean,
                        autoPlay: boolean,
                        blocking: spaceSeparated,
                        capture: null,
                        charSet: null,
                        checked: boolean,
                        cite: null,
                        className: spaceSeparated,
                        cols: number,
                        colSpan: null,
                        content: null,
                        contentEditable: booleanish,
                        controls: boolean,
                        controlsList: spaceSeparated,
                        coords: number | commaSeparated,
                        crossOrigin: null,
                        data: null,
                        dateTime: null,
                        decoding: null,
                        default: boolean,
                        defer: boolean,
                        dir: null,
                        dirName: null,
                        disabled: boolean,
                        download: overloadedBoolean,
                        draggable: booleanish,
                        encType: null,
                        enterKeyHint: null,
                        fetchPriority: null,
                        form: null,
                        formAction: null,
                        formEncType: null,
                        formMethod: null,
                        formNoValidate: boolean,
                        formTarget: null,
                        headers: spaceSeparated,
                        height: number,
                        hidden: boolean,
                        high: number,
                        href: null,
                        hrefLang: null,
                        htmlFor: spaceSeparated,
                        httpEquiv: spaceSeparated,
                        id: null,
                        imageSizes: null,
                        imageSrcSet: null,
                        inert: boolean,
                        inputMode: null,
                        integrity: null,
                        is: null,
                        isMap: boolean,
                        itemId: null,
                        itemProp: spaceSeparated,
                        itemRef: spaceSeparated,
                        itemScope: boolean,
                        itemType: spaceSeparated,
                        kind: null,
                        label: null,
                        lang: null,
                        language: null,
                        list: null,
                        loading: null,
                        loop: boolean,
                        low: number,
                        manifest: null,
                        max: null,
                        maxLength: number,
                        media: null,
                        method: null,
                        min: null,
                        minLength: number,
                        multiple: boolean,
                        muted: boolean,
                        name: null,
                        nonce: null,
                        noModule: boolean,
                        noValidate: boolean,
                        onAbort: null,
                        onAfterPrint: null,
                        onAuxClick: null,
                        onBeforeMatch: null,
                        onBeforePrint: null,
                        onBeforeToggle: null,
                        onBeforeUnload: null,
                        onBlur: null,
                        onCancel: null,
                        onCanPlay: null,
                        onCanPlayThrough: null,
                        onChange: null,
                        onClick: null,
                        onClose: null,
                        onContextLost: null,
                        onContextMenu: null,
                        onContextRestored: null,
                        onCopy: null,
                        onCueChange: null,
                        onCut: null,
                        onDblClick: null,
                        onDrag: null,
                        onDragEnd: null,
                        onDragEnter: null,
                        onDragExit: null,
                        onDragLeave: null,
                        onDragOver: null,
                        onDragStart: null,
                        onDrop: null,
                        onDurationChange: null,
                        onEmptied: null,
                        onEnded: null,
                        onError: null,
                        onFocus: null,
                        onFormData: null,
                        onHashChange: null,
                        onInput: null,
                        onInvalid: null,
                        onKeyDown: null,
                        onKeyPress: null,
                        onKeyUp: null,
                        onLanguageChange: null,
                        onLoad: null,
                        onLoadedData: null,
                        onLoadedMetadata: null,
                        onLoadEnd: null,
                        onLoadStart: null,
                        onMessage: null,
                        onMessageError: null,
                        onMouseDown: null,
                        onMouseEnter: null,
                        onMouseLeave: null,
                        onMouseMove: null,
                        onMouseOut: null,
                        onMouseOver: null,
                        onMouseUp: null,
                        onOffline: null,
                        onOnline: null,
                        onPageHide: null,
                        onPageShow: null,
                        onPaste: null,
                        onPause: null,
                        onPlay: null,
                        onPlaying: null,
                        onPopState: null,
                        onProgress: null,
                        onRateChange: null,
                        onRejectionHandled: null,
                        onReset: null,
                        onResize: null,
                        onScroll: null,
                        onScrollEnd: null,
                        onSecurityPolicyViolation: null,
                        onSeeked: null,
                        onSeeking: null,
                        onSelect: null,
                        onSlotChange: null,
                        onStalled: null,
                        onStorage: null,
                        onSubmit: null,
                        onSuspend: null,
                        onTimeUpdate: null,
                        onToggle: null,
                        onUnhandledRejection: null,
                        onUnload: null,
                        onVolumeChange: null,
                        onWaiting: null,
                        onWheel: null,
                        open: boolean,
                        optimum: number,
                        pattern: null,
                        ping: spaceSeparated,
                        placeholder: null,
                        playsInline: boolean,
                        popover: null,
                        popoverTarget: null,
                        popoverTargetAction: null,
                        poster: null,
                        preload: null,
                        readOnly: boolean,
                        referrerPolicy: null,
                        rel: spaceSeparated,
                        required: boolean,
                        reversed: boolean,
                        rows: number,
                        rowSpan: number,
                        sandbox: spaceSeparated,
                        scope: null,
                        scoped: boolean,
                        seamless: boolean,
                        selected: boolean,
                        shadowRootClonable: boolean,
                        shadowRootDelegatesFocus: boolean,
                        shadowRootMode: null,
                        shape: null,
                        size: number,
                        sizes: null,
                        slot: null,
                        span: number,
                        spellCheck: booleanish,
                        src: null,
                        srcDoc: null,
                        srcLang: null,
                        srcSet: null,
                        start: number,
                        step: null,
                        style: null,
                        tabIndex: number,
                        target: null,
                        title: null,
                        translate: null,
                        type: null,
                        typeMustMatch: boolean,
                        useMap: null,
                        value: booleanish,
                        width: number,
                        wrap: null,
                        writingSuggestions: null,
                        // Legacy.
                        // See: https://html.spec.whatwg.org/#other-elements,-attributes-and-apis
                        align: null,
                        // Several. Use CSS `text-align` instead,
                        aLink: null,
                        // `<body>`. Use CSS `a:active {color}` instead
                        archive: spaceSeparated,
                        // `<object>`. List of URIs to archives
                        axis: null,
                        // `<td>` and `<th>`. Use `scope` on `<th>`
                        background: null,
                        // `<body>`. Use CSS `background-image` instead
                        bgColor: null,
                        // `<body>` and table elements. Use CSS `background-color` instead
                        border: number,
                        // `<table>`. Use CSS `border-width` instead,
                        borderColor: null,
                        // `<table>`. Use CSS `border-color` instead,
                        bottomMargin: number,
                        // `<body>`
                        cellPadding: null,
                        // `<table>`
                        cellSpacing: null,
                        // `<table>`
                        char: null,
                        // Several table elements. When `align=char`, sets the character to align on
                        charOff: null,
                        // Several table elements. When `char`, offsets the alignment
                        classId: null,
                        // `<object>`
                        clear: null,
                        // `<br>`. Use CSS `clear` instead
                        code: null,
                        // `<object>`
                        codeBase: null,
                        // `<object>`
                        codeType: null,
                        // `<object>`
                        color: null,
                        // `<font>` and `<hr>`. Use CSS instead
                        compact: boolean,
                        // Lists. Use CSS to reduce space between items instead
                        declare: boolean,
                        // `<object>`
                        event: null,
                        // `<script>`
                        face: null,
                        // `<font>`. Use CSS instead
                        frame: null,
                        // `<table>`
                        frameBorder: null,
                        // `<iframe>`. Use CSS `border` instead
                        hSpace: number,
                        // `<img>` and `<object>`
                        leftMargin: number,
                        // `<body>`
                        link: null,
                        // `<body>`. Use CSS `a:link {color: *}` instead
                        longDesc: null,
                        // `<frame>`, `<iframe>`, and `<img>`. Use an `<a>`
                        lowSrc: null,
                        // `<img>`. Use a `<picture>`
                        marginHeight: number,
                        // `<body>`
                        marginWidth: number,
                        // `<body>`
                        noResize: boolean,
                        // `<frame>`
                        noHref: boolean,
                        // `<area>`. Use no href instead of an explicit `nohref`
                        noShade: boolean,
                        // `<hr>`. Use background-color and height instead of borders
                        noWrap: boolean,
                        // `<td>` and `<th>`
                        object: null,
                        // `<applet>`
                        profile: null,
                        // `<head>`
                        prompt: null,
                        // `<isindex>`
                        rev: null,
                        // `<link>`
                        rightMargin: number,
                        // `<body>`
                        rules: null,
                        // `<table>`
                        scheme: null,
                        // `<meta>`
                        scrolling: booleanish,
                        // `<frame>`. Use overflow in the child context
                        standby: null,
                        // `<object>`
                        summary: null,
                        // `<table>`
                        text: null,
                        // `<body>`. Use CSS `color` instead
                        topMargin: number,
                        // `<body>`
                        valueType: null,
                        // `<param>`
                        version: null,
                        // `<html>`. Use a doctype.
                        vAlign: null,
                        // Several. Use CSS `vertical-align` instead
                        vLink: null,
                        // `<body>`. Use CSS `a:visited {color}` instead
                        vSpace: number,
                        // `<img>` and `<object>`

                        // Non-standard Properties.
                        allowTransparency: null,
                        autoCorrect: null,
                        autoSave: null,
                        disablePictureInPicture: boolean,
                        disableRemotePlayback: boolean,
                        prefix: null,
                        property: null,
                        results: number,
                        security: null,
                        unselectable: null
                    }
                });
                var svg$1 = create({
                    space: 'svg',
                    attributes: {
                        accentHeight: 'accent-height',
                        alignmentBaseline: 'alignment-baseline',
                        arabicForm: 'arabic-form',
                        baselineShift: 'baseline-shift',
                        capHeight: 'cap-height',
                        className: 'class',
                        clipPath: 'clip-path',
                        clipRule: 'clip-rule',
                        colorInterpolation: 'color-interpolation',
                        colorInterpolationFilters: 'color-interpolation-filters',
                        colorProfile: 'color-profile',
                        colorRendering: 'color-rendering',
                        crossOrigin: 'crossorigin',
                        dataType: 'datatype',
                        dominantBaseline: 'dominant-baseline',
                        enableBackground: 'enable-background',
                        fillOpacity: 'fill-opacity',
                        fillRule: 'fill-rule',
                        floodColor: 'flood-color',
                        floodOpacity: 'flood-opacity',
                        fontFamily: 'font-family',
                        fontSize: 'font-size',
                        fontSizeAdjust: 'font-size-adjust',
                        fontStretch: 'font-stretch',
                        fontStyle: 'font-style',
                        fontVariant: 'font-variant',
                        fontWeight: 'font-weight',
                        glyphName: 'glyph-name',
                        glyphOrientationHorizontal: 'glyph-orientation-horizontal',
                        glyphOrientationVertical: 'glyph-orientation-vertical',
                        hrefLang: 'hreflang',
                        horizAdvX: 'horiz-adv-x',
                        horizOriginX: 'horiz-origin-x',
                        horizOriginY: 'horiz-origin-y',
                        imageRendering: 'image-rendering',
                        letterSpacing: 'letter-spacing',
                        lightingColor: 'lighting-color',
                        markerEnd: 'marker-end',
                        markerMid: 'marker-mid',
                        markerStart: 'marker-start',
                        navDown: 'nav-down',
                        navDownLeft: 'nav-down-left',
                        navDownRight: 'nav-down-right',
                        navLeft: 'nav-left',
                        navNext: 'nav-next',
                        navPrev: 'nav-prev',
                        navRight: 'nav-right',
                        navUp: 'nav-up',
                        navUpLeft: 'nav-up-left',
                        navUpRight: 'nav-up-right',
                        onAbort: 'onabort',
                        onActivate: 'onactivate',
                        onAfterPrint: 'onafterprint',
                        onBeforePrint: 'onbeforeprint',
                        onBegin: 'onbegin',
                        onCancel: 'oncancel',
                        onCanPlay: 'oncanplay',
                        onCanPlayThrough: 'oncanplaythrough',
                        onChange: 'onchange',
                        onClick: 'onclick',
                        onClose: 'onclose',
                        onCopy: 'oncopy',
                        onCueChange: 'oncuechange',
                        onCut: 'oncut',
                        onDblClick: 'ondblclick',
                        onDrag: 'ondrag',
                        onDragEnd: 'ondragend',
                        onDragEnter: 'ondragenter',
                        onDragExit: 'ondragexit',
                        onDragLeave: 'ondragleave',
                        onDragOver: 'ondragover',
                        onDragStart: 'ondragstart',
                        onDrop: 'ondrop',
                        onDurationChange: 'ondurationchange',
                        onEmptied: 'onemptied',
                        onEnd: 'onend',
                        onEnded: 'onended',
                        onError: 'onerror',
                        onFocus: 'onfocus',
                        onFocusIn: 'onfocusin',
                        onFocusOut: 'onfocusout',
                        onHashChange: 'onhashchange',
                        onInput: 'oninput',
                        onInvalid: 'oninvalid',
                        onKeyDown: 'onkeydown',
                        onKeyPress: 'onkeypress',
                        onKeyUp: 'onkeyup',
                        onLoad: 'onload',
                        onLoadedData: 'onloadeddata',
                        onLoadedMetadata: 'onloadedmetadata',
                        onLoadStart: 'onloadstart',
                        onMessage: 'onmessage',
                        onMouseDown: 'onmousedown',
                        onMouseEnter: 'onmouseenter',
                        onMouseLeave: 'onmouseleave',
                        onMouseMove: 'onmousemove',
                        onMouseOut: 'onmouseout',
                        onMouseOver: 'onmouseover',
                        onMouseUp: 'onmouseup',
                        onMouseWheel: 'onmousewheel',
                        onOffline: 'onoffline',
                        onOnline: 'ononline',
                        onPageHide: 'onpagehide',
                        onPageShow: 'onpageshow',
                        onPaste: 'onpaste',
                        onPause: 'onpause',
                        onPlay: 'onplay',
                        onPlaying: 'onplaying',
                        onPopState: 'onpopstate',
                        onProgress: 'onprogress',
                        onRateChange: 'onratechange',
                        onRepeat: 'onrepeat',
                        onReset: 'onreset',
                        onResize: 'onresize',
                        onScroll: 'onscroll',
                        onSeeked: 'onseeked',
                        onSeeking: 'onseeking',
                        onSelect: 'onselect',
                        onShow: 'onshow',
                        onStalled: 'onstalled',
                        onStorage: 'onstorage',
                        onSubmit: 'onsubmit',
                        onSuspend: 'onsuspend',
                        onTimeUpdate: 'ontimeupdate',
                        onToggle: 'ontoggle',
                        onUnload: 'onunload',
                        onVolumeChange: 'onvolumechange',
                        onWaiting: 'onwaiting',
                        onZoom: 'onzoom',
                        overlinePosition: 'overline-position',
                        overlineThickness: 'overline-thickness',
                        paintOrder: 'paint-order',
                        panose1: 'panose-1',
                        pointerEvents: 'pointer-events',
                        referrerPolicy: 'referrerpolicy',
                        renderingIntent: 'rendering-intent',
                        shapeRendering: 'shape-rendering',
                        stopColor: 'stop-color',
                        stopOpacity: 'stop-opacity',
                        strikethroughPosition: 'strikethrough-position',
                        strikethroughThickness: 'strikethrough-thickness',
                        strokeDashArray: 'stroke-dasharray',
                        strokeDashOffset: 'stroke-dashoffset',
                        strokeLineCap: 'stroke-linecap',
                        strokeLineJoin: 'stroke-linejoin',
                        strokeMiterLimit: 'stroke-miterlimit',
                        strokeOpacity: 'stroke-opacity',
                        strokeWidth: 'stroke-width',
                        tabIndex: 'tabindex',
                        textAnchor: 'text-anchor',
                        textDecoration: 'text-decoration',
                        textRendering: 'text-rendering',
                        transformOrigin: 'transform-origin',
                        typeOf: 'typeof',
                        underlinePosition: 'underline-position',
                        underlineThickness: 'underline-thickness',
                        unicodeBidi: 'unicode-bidi',
                        unicodeRange: 'unicode-range',
                        unitsPerEm: 'units-per-em',
                        vAlphabetic: 'v-alphabetic',
                        vHanging: 'v-hanging',
                        vIdeographic: 'v-ideographic',
                        vMathematical: 'v-mathematical',
                        vectorEffect: 'vector-effect',
                        vertAdvY: 'vert-adv-y',
                        vertOriginX: 'vert-origin-x',
                        vertOriginY: 'vert-origin-y',
                        wordSpacing: 'word-spacing',
                        writingMode: 'writing-mode',
                        xHeight: 'x-height',
                        // These were camelcased in Tiny. Now lowercased in SVG 2
                        playbackOrder: 'playbackorder',
                        timelineBegin: 'timelinebegin'
                    },
                    transform: caseSensitiveTransform,
                    properties: {
                        about: commaOrSpaceSeparated,
                        accentHeight: number,
                        accumulate: null,
                        additive: null,
                        alignmentBaseline: null,
                        alphabetic: number,
                        amplitude: number,
                        arabicForm: null,
                        ascent: number,
                        attributeName: null,
                        attributeType: null,
                        azimuth: number,
                        bandwidth: null,
                        baselineShift: null,
                        baseFrequency: null,
                        baseProfile: null,
                        bbox: null,
                        begin: null,
                        bias: number,
                        by: null,
                        calcMode: null,
                        capHeight: number,
                        className: spaceSeparated,
                        clip: null,
                        clipPath: null,
                        clipPathUnits: null,
                        clipRule: null,
                        color: null,
                        colorInterpolation: null,
                        colorInterpolationFilters: null,
                        colorProfile: null,
                        colorRendering: null,
                        content: null,
                        contentScriptType: null,
                        contentStyleType: null,
                        crossOrigin: null,
                        cursor: null,
                        cx: null,
                        cy: null,
                        d: null,
                        dataType: null,
                        defaultAction: null,
                        descent: number,
                        diffuseConstant: number,
                        direction: null,
                        display: null,
                        dur: null,
                        divisor: number,
                        dominantBaseline: null,
                        download: boolean,
                        dx: null,
                        dy: null,
                        edgeMode: null,
                        editable: null,
                        elevation: number,
                        enableBackground: null,
                        end: null,
                        event: null,
                        exponent: number,
                        externalResourcesRequired: null,
                        fill: null,
                        fillOpacity: number,
                        fillRule: null,
                        filter: null,
                        filterRes: null,
                        filterUnits: null,
                        floodColor: null,
                        floodOpacity: null,
                        focusable: null,
                        focusHighlight: null,
                        fontFamily: null,
                        fontSize: null,
                        fontSizeAdjust: null,
                        fontStretch: null,
                        fontStyle: null,
                        fontVariant: null,
                        fontWeight: null,
                        format: null,
                        fr: null,
                        from: null,
                        fx: null,
                        fy: null,
                        g1: commaSeparated,
                        g2: commaSeparated,
                        glyphName: commaSeparated,
                        glyphOrientationHorizontal: null,
                        glyphOrientationVertical: null,
                        glyphRef: null,
                        gradientTransform: null,
                        gradientUnits: null,
                        handler: null,
                        hanging: number,
                        hatchContentUnits: null,
                        hatchUnits: null,
                        height: null,
                        href: null,
                        hrefLang: null,
                        horizAdvX: number,
                        horizOriginX: number,
                        horizOriginY: number,
                        id: null,
                        ideographic: number,
                        imageRendering: null,
                        initialVisibility: null,
                        in: null,
                        in2: null,
                        intercept: number,
                        k: number,
                        k1: number,
                        k2: number,
                        k3: number,
                        k4: number,
                        kernelMatrix: commaOrSpaceSeparated,
                        kernelUnitLength: null,
                        keyPoints: null,
                        // SEMI_COLON_SEPARATED
                        keySplines: null,
                        // SEMI_COLON_SEPARATED
                        keyTimes: null,
                        // SEMI_COLON_SEPARATED
                        kerning: null,
                        lang: null,
                        lengthAdjust: null,
                        letterSpacing: null,
                        lightingColor: null,
                        limitingConeAngle: number,
                        local: null,
                        markerEnd: null,
                        markerMid: null,
                        markerStart: null,
                        markerHeight: null,
                        markerUnits: null,
                        markerWidth: null,
                        mask: null,
                        maskContentUnits: null,
                        maskUnits: null,
                        mathematical: null,
                        max: null,
                        media: null,
                        mediaCharacterEncoding: null,
                        mediaContentEncodings: null,
                        mediaSize: number,
                        mediaTime: null,
                        method: null,
                        min: null,
                        mode: null,
                        name: null,
                        navDown: null,
                        navDownLeft: null,
                        navDownRight: null,
                        navLeft: null,
                        navNext: null,
                        navPrev: null,
                        navRight: null,
                        navUp: null,
                        navUpLeft: null,
                        navUpRight: null,
                        numOctaves: null,
                        observer: null,
                        offset: null,
                        onAbort: null,
                        onActivate: null,
                        onAfterPrint: null,
                        onBeforePrint: null,
                        onBegin: null,
                        onCancel: null,
                        onCanPlay: null,
                        onCanPlayThrough: null,
                        onChange: null,
                        onClick: null,
                        onClose: null,
                        onCopy: null,
                        onCueChange: null,
                        onCut: null,
                        onDblClick: null,
                        onDrag: null,
                        onDragEnd: null,
                        onDragEnter: null,
                        onDragExit: null,
                        onDragLeave: null,
                        onDragOver: null,
                        onDragStart: null,
                        onDrop: null,
                        onDurationChange: null,
                        onEmptied: null,
                        onEnd: null,
                        onEnded: null,
                        onError: null,
                        onFocus: null,
                        onFocusIn: null,
                        onFocusOut: null,
                        onHashChange: null,
                        onInput: null,
                        onInvalid: null,
                        onKeyDown: null,
                        onKeyPress: null,
                        onKeyUp: null,
                        onLoad: null,
                        onLoadedData: null,
                        onLoadedMetadata: null,
                        onLoadStart: null,
                        onMessage: null,
                        onMouseDown: null,
                        onMouseEnter: null,
                        onMouseLeave: null,
                        onMouseMove: null,
                        onMouseOut: null,
                        onMouseOver: null,
                        onMouseUp: null,
                        onMouseWheel: null,
                        onOffline: null,
                        onOnline: null,
                        onPageHide: null,
                        onPageShow: null,
                        onPaste: null,
                        onPause: null,
                        onPlay: null,
                        onPlaying: null,
                        onPopState: null,
                        onProgress: null,
                        onRateChange: null,
                        onRepeat: null,
                        onReset: null,
                        onResize: null,
                        onScroll: null,
                        onSeeked: null,
                        onSeeking: null,
                        onSelect: null,
                        onShow: null,
                        onStalled: null,
                        onStorage: null,
                        onSubmit: null,
                        onSuspend: null,
                        onTimeUpdate: null,
                        onToggle: null,
                        onUnload: null,
                        onVolumeChange: null,
                        onWaiting: null,
                        onZoom: null,
                        opacity: null,
                        operator: null,
                        order: null,
                        orient: null,
                        orientation: null,
                        origin: null,
                        overflow: null,
                        overlay: null,
                        overlinePosition: number,
                        overlineThickness: number,
                        paintOrder: null,
                        panose1: null,
                        path: null,
                        pathLength: number,
                        patternContentUnits: null,
                        patternTransform: null,
                        patternUnits: null,
                        phase: null,
                        ping: spaceSeparated,
                        pitch: null,
                        playbackOrder: null,
                        pointerEvents: null,
                        points: null,
                        pointsAtX: number,
                        pointsAtY: number,
                        pointsAtZ: number,
                        preserveAlpha: null,
                        preserveAspectRatio: null,
                        primitiveUnits: null,
                        propagate: null,
                        property: commaOrSpaceSeparated,
                        r: null,
                        radius: null,
                        referrerPolicy: null,
                        refX: null,
                        refY: null,
                        rel: commaOrSpaceSeparated,
                        rev: commaOrSpaceSeparated,
                        renderingIntent: null,
                        repeatCount: null,
                        repeatDur: null,
                        requiredExtensions: commaOrSpaceSeparated,
                        requiredFeatures: commaOrSpaceSeparated,
                        requiredFonts: commaOrSpaceSeparated,
                        requiredFormats: commaOrSpaceSeparated,
                        resource: null,
                        restart: null,
                        result: null,
                        rotate: null,
                        rx: null,
                        ry: null,
                        scale: null,
                        seed: null,
                        shapeRendering: null,
                        side: null,
                        slope: null,
                        snapshotTime: null,
                        specularConstant: number,
                        specularExponent: number,
                        spreadMethod: null,
                        spacing: null,
                        startOffset: null,
                        stdDeviation: null,
                        stemh: null,
                        stemv: null,
                        stitchTiles: null,
                        stopColor: null,
                        stopOpacity: null,
                        strikethroughPosition: number,
                        strikethroughThickness: number,
                        string: null,
                        stroke: null,
                        strokeDashArray: commaOrSpaceSeparated,
                        strokeDashOffset: null,
                        strokeLineCap: null,
                        strokeLineJoin: null,
                        strokeMiterLimit: number,
                        strokeOpacity: number,
                        strokeWidth: null,
                        style: null,
                        surfaceScale: number,
                        syncBehavior: null,
                        syncBehaviorDefault: null,
                        syncMaster: null,
                        syncTolerance: null,
                        syncToleranceDefault: null,
                        systemLanguage: commaOrSpaceSeparated,
                        tabIndex: number,
                        tableValues: null,
                        target: null,
                        targetX: number,
                        targetY: number,
                        textAnchor: null,
                        textDecoration: null,
                        textRendering: null,
                        textLength: null,
                        timelineBegin: null,
                        title: null,
                        transformBehavior: null,
                        type: null,
                        typeOf: commaOrSpaceSeparated,
                        to: null,
                        transform: null,
                        transformOrigin: null,
                        u1: null,
                        u2: null,
                        underlinePosition: number,
                        underlineThickness: number,
                        unicode: null,
                        unicodeBidi: null,
                        unicodeRange: null,
                        unitsPerEm: number,
                        values: null,
                        vAlphabetic: number,
                        vMathematical: number,
                        vectorEffect: null,
                        vHanging: number,
                        vIdeographic: number,
                        version: null,
                        vertAdvY: number,
                        vertOriginX: number,
                        vertOriginY: number,
                        viewBox: null,
                        viewTarget: null,
                        visibility: null,
                        width: null,
                        widths: null,
                        wordSpacing: null,
                        writingMode: null,
                        x: null,
                        x1: null,
                        x2: null,
                        xChannelSelector: null,
                        xHeight: number,
                        y: null,
                        y1: null,
                        y2: null,
                        yChannelSelector: null,
                        z: null,
                        zoomAndPan: null
                    }
                });

                /**
                 * @typedef {import('./util/schema.js').Schema} Schema
                 */

                var valid = /^data[-\w.:]+$/i;
                var dash = /-[a-z]/g;
                var cap = /[A-Z]/g;

                /**
                 * @param {Schema} schema
                 * @param {string} value
                 * @returns {Info}
                 */
                function find(schema, value) {
                    var normal = normalize(value);
                    var prop = value;
                    var Type = Info;
                    if (normal in schema.normal) {
                        return schema.property[schema.normal[normal]];
                    }
                    if (normal.length > 4 && normal.slice(0, 4) === 'data' && valid.test(value)) {
                        // Attribute or property.
                        if (value.charAt(4) === '-') {
                            // Turn it into a property.
                            var rest = value.slice(5).replace(dash, camelcase);
                            prop = 'data' + rest.charAt(0).toUpperCase() + rest.slice(1);
                        } else {
                            // Turn it into an attribute.
                            var _rest = value.slice(4);
                            if (!dash.test(_rest)) {
                                var dashes = _rest.replace(cap, kebab);
                                if (dashes.charAt(0) !== '-') {
                                    dashes = '-' + dashes;
                                }
                                value = 'data' + dashes;
                            }
                        }
                        Type = DefinedInfo;
                    }
                    return new Type(prop, value);
                }

                /**
                 * @param {string} $0
                 * @returns {string}
                 */
                function kebab($0) {
                    return '-' + $0.toLowerCase();
                }

                /**
                 * @param {string} $0
                 * @returns {string}
                 */
                function camelcase($0) {
                    return $0.charAt(1).toUpperCase();
                }

                /**
                 * @typedef {import('./lib/util/info.js').Info} Info
                 * @typedef {import('./lib/util/schema.js').Schema} Schema
                 */

                var html$2 = merge([xml, xlink, xmlns, aria, html$3], 'html');
                var svg = merge([xml, xlink, xmlns, aria, svg$1], 'svg');

                /**
                 * @callback Handler
                 *   Handle a value, with a certain ID field set to a certain value.
                 *   The ID field is passed to `zwitch`, and it’s value is this function’s
                 *   place on the `handlers` record.
                 * @param {...any} parameters
                 *   Arbitrary parameters passed to the zwitch.
                 *   The first will be an object with a certain ID field set to a certain value.
                 * @returns {any}
                 *   Anything!
                 */

                /**
                 * @callback UnknownHandler
                 *   Handle values that do have a certain ID field, but it’s set to a value
                 *   that is not listed in the `handlers` record.
                 * @param {unknown} value
                 *   An object with a certain ID field set to an unknown value.
                 * @param {...any} rest
                 *   Arbitrary parameters passed to the zwitch.
                 * @returns {any}
                 *   Anything!
                 */

                /**
                 * @callback InvalidHandler
                 *   Handle values that do not have a certain ID field.
                 * @param {unknown} value
                 *   Any unknown value.
                 * @param {...any} rest
                 *   Arbitrary parameters passed to the zwitch.
                 * @returns {void|null|undefined|never}
                 *   This should crash or return nothing.
                 */

                /**
                 * @template {InvalidHandler} [Invalid=InvalidHandler]
                 * @template {UnknownHandler} [Unknown=UnknownHandler]
                 * @template {Record<string, Handler>} [Handlers=Record<string, Handler>]
                 * @typedef Options
                 *   Configuration (required).
                 * @property {Invalid} [invalid]
                 *   Handler to use for invalid values.
                 * @property {Unknown} [unknown]
                 *   Handler to use for unknown values.
                 * @property {Handlers} [handlers]
                 *   Handlers to use.
                 */

                var own$2 = {}.hasOwnProperty;

                /**
                 * Handle values based on a field.
                 *
                 * @template {InvalidHandler} [Invalid=InvalidHandler]
                 * @template {UnknownHandler} [Unknown=UnknownHandler]
                 * @template {Record<string, Handler>} [Handlers=Record<string, Handler>]
                 * @param {string} key
                 *   Field to switch on.
                 * @param {Options<Invalid, Unknown, Handlers>} [options]
                 *   Configuration (required).
                 * @returns {{unknown: Unknown, invalid: Invalid, handlers: Handlers, (...parameters: Parameters<Handlers[keyof Handlers]>): ReturnType<Handlers[keyof Handlers]>, (...parameters: Parameters<Unknown>): ReturnType<Unknown>}}
                 */
                function zwitch(key, options) {
                    var settings = options || {};

                    /**
                     * Handle one value.
                     *
                     * Based on the bound `key`, a respective handler will be called.
                     * If `value` is not an object, or doesn’t have a `key` property, the special
                     * “invalid” handler will be called.
                     * If `value` has an unknown `key`, the special “unknown” handler will be
                     * called.
                     *
                     * All arguments, and the context object, are passed through to the handler,
                     * and it’s result is returned.
                     *
                     * @this {unknown}
                     *   Any context object.
                     * @param {unknown} [value]
                     *   Any value.
                     * @param {...unknown} parameters
                     *   Arbitrary parameters passed to the zwitch.
                     * @property {Handler} invalid
                     *   Handle for values that do not have a certain ID field.
                     * @property {Handler} unknown
                     *   Handle values that do have a certain ID field, but it’s set to a value
                     *   that is not listed in the `handlers` record.
                     * @property {Handlers} handlers
                     *   Record of handlers.
                     * @returns {unknown}
                     *   Anything.
                     */
                    function one(value) {
                        /** @type {Handler|undefined} */
                        var fn = one.invalid;
                        var handlers = one.handlers;
                        if (value && own$2.call(value, key)) {
                            // @ts-expect-error Indexable.
                            var id = String(value[key]);
                            // @ts-expect-error Indexable.
                            fn = own$2.call(handlers, id) ? handlers[id] : one.unknown;
                        }
                        if (fn) {
                            var _fn;
                            for (var _len3 = arguments.length, parameters = new Array(_len3 > 1 ? _len3 - 1 : 0), _key4 = 1; _key4 < _len3; _key4++) {
                                parameters[_key4 - 1] = arguments[_key4];
                            }
                            return (_fn = fn).call.apply(_fn, [this, value].concat(parameters));
                        }
                    }

                    one.handlers = settings.handlers || {};
                    one.invalid = settings.invalid;
                    one.unknown = settings.unknown;

                    // @ts-expect-error: matches!
                    return one;
                }

                /**
                 * @typedef CoreOptions
                 * @property {ReadonlyArray<string>} [subset=[]]
                 *   Whether to only escape the given subset of characters.
                 * @property {boolean} [escapeOnly=false]
                 *   Whether to only escape possibly dangerous characters.
                 *   Those characters are `"`, `&`, `'`, `<`, `>`, and `` ` ``.
                 *
                 * @typedef FormatOptions
                 * @property {(code: number, next: number, options: CoreWithFormatOptions) => string} format
                 *   Format strategy.
                 *
                 * @typedef {CoreOptions & FormatOptions & import('./util/format-smart.js').FormatSmartOptions} CoreWithFormatOptions
                 */

                var defaultSubsetRegex = /["&'<>`]/g;
                var surrogatePairsRegex = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
                var controlCharactersRegex =
                    // eslint-disable-next-line no-control-regex, unicorn/no-hex-escape
                    /[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g;
                var regexEscapeRegex = /[|\\{}()[\]^$+*?.]/g;

                /** @type {WeakMap<ReadonlyArray<string>, RegExp>} */
                var subsetToRegexCache = new WeakMap();

                /**
                 * Encode certain characters in `value`.
                 *
                 * @param {string} value
                 * @param {CoreWithFormatOptions} options
                 * @returns {string}
                 */
                function core(value, options) {
                    value = value.replace(options.subset ? charactersToExpressionCached(options.subset) : defaultSubsetRegex, basic);
                    if (options.subset || options.escapeOnly) {
                        return value;
                    }
                    return value
                        // Surrogate pairs.
                        .replace(surrogatePairsRegex, surrogate)
                        // BMP control characters (C0 except for LF, CR, SP; DEL; and some more
                        // non-ASCII ones).
                        .replace(controlCharactersRegex, basic);

                    /**
                     * @param {string} pair
                     * @param {number} index
                     * @param {string} all
                     */
                    function surrogate(pair, index, all) {
                        return options.format((pair.charCodeAt(0) - 0xd800) * 0x400 + pair.charCodeAt(1) - 0xdc00 + 0x10000, all.charCodeAt(index + 2), options);
                    }

                    /**
                     * @param {string} character
                     * @param {number} index
                     * @param {string} all
                     */
                    function basic(character, index, all) {
                        return options.format(character.charCodeAt(0), all.charCodeAt(index + 1), options);
                    }
                }

                /**
                 * A wrapper function that caches the result of `charactersToExpression` with a WeakMap.
                 * This can improve performance when tooling calls `charactersToExpression` repeatedly
                 * with the same subset.
                 *
                 * @param {ReadonlyArray<string>} subset
                 * @returns {RegExp}
                 */
                function charactersToExpressionCached(subset) {
                    var cached = subsetToRegexCache.get(subset);
                    if (!cached) {
                        cached = charactersToExpression(subset);
                        subsetToRegexCache.set(subset, cached);
                    }
                    return cached;
                }

                /**
                 * @param {ReadonlyArray<string>} subset
                 * @returns {RegExp}
                 */
                function charactersToExpression(subset) {
                    /** @type {Array<string>} */
                    var groups = [];
                    var index = -1;
                    while (++index < subset.length) {
                        groups.push(subset[index].replace(regexEscapeRegex, '\\$&'));
                    }
                    return new RegExp('(?:' + groups.join('|') + ')', 'g');
                }

                var hexadecimalRegex = /[\dA-Fa-f]/;

                /**
                 * Configurable ways to encode characters as hexadecimal references.
                 *
                 * @param {number} code
                 * @param {number} next
                 * @param {boolean|undefined} omit
                 * @returns {string}
                 */
                function toHexadecimal(code, next, omit) {
                    var value = '&#x' + code.toString(16).toUpperCase();
                    return omit && next && !hexadecimalRegex.test(String.fromCharCode(next)) ? value : value + ';';
                }

                var decimalRegex = /\d/;

                /**
                 * Configurable ways to encode characters as decimal references.
                 *
                 * @param {number} code
                 * @param {number} next
                 * @param {boolean|undefined} omit
                 * @returns {string}
                 */
                function toDecimal(code, next, omit) {
                    var value = '&#' + String(code);
                    return omit && next && !decimalRegex.test(String.fromCharCode(next)) ? value : value + ';';
                }

                /**
                 * List of legacy HTML named character references that don’t need a trailing semicolon.
                 *
                 * @type {Array<string>}
                 */
                var characterEntitiesLegacy = ['AElig', 'AMP', 'Aacute', 'Acirc', 'Agrave', 'Aring', 'Atilde', 'Auml', 'COPY', 'Ccedil', 'ETH', 'Eacute', 'Ecirc', 'Egrave', 'Euml', 'GT', 'Iacute', 'Icirc', 'Igrave', 'Iuml', 'LT', 'Ntilde', 'Oacute', 'Ocirc', 'Ograve', 'Oslash', 'Otilde', 'Ouml', 'QUOT', 'REG', 'THORN', 'Uacute', 'Ucirc', 'Ugrave', 'Uuml', 'Yacute', 'aacute', 'acirc', 'acute', 'aelig', 'agrave', 'amp', 'aring', 'atilde', 'auml', 'brvbar', 'ccedil', 'cedil', 'cent', 'copy', 'curren', 'deg', 'divide', 'eacute', 'ecirc', 'egrave', 'eth', 'euml', 'frac12', 'frac14', 'frac34', 'gt', 'iacute', 'icirc', 'iexcl', 'igrave', 'iquest', 'iuml', 'laquo', 'lt', 'macr', 'micro', 'middot', 'nbsp', 'not', 'ntilde', 'oacute', 'ocirc', 'ograve', 'ordf', 'ordm', 'oslash', 'otilde', 'ouml', 'para', 'plusmn', 'pound', 'quot', 'raquo', 'reg', 'sect', 'shy', 'sup1', 'sup2', 'sup3', 'szlig', 'thorn', 'times', 'uacute', 'ucirc', 'ugrave', 'uml', 'uuml', 'yacute', 'yen', 'yuml'];

                /**
                 * Map of named character references from HTML 4.
                 *
                 * @type {Record<string, string>}
                 */
                var characterEntitiesHtml4 = {
                    nbsp: ' ',
                    iexcl: '¡',
                    cent: '¢',
                    pound: '£',
                    curren: '¤',
                    yen: '¥',
                    brvbar: '¦',
                    sect: '§',
                    uml: '¨',
                    copy: '©',
                    ordf: 'ª',
                    laquo: '«',
                    not: '¬',
                    shy: '­',
                    reg: '®',
                    macr: '¯',
                    deg: '°',
                    plusmn: '±',
                    sup2: '²',
                    sup3: '³',
                    acute: '´',
                    micro: 'µ',
                    para: '¶',
                    middot: '·',
                    cedil: '¸',
                    sup1: '¹',
                    ordm: 'º',
                    raquo: '»',
                    frac14: '¼',
                    frac12: '½',
                    frac34: '¾',
                    iquest: '¿',
                    Agrave: 'À',
                    Aacute: 'Á',
                    Acirc: 'Â',
                    Atilde: 'Ã',
                    Auml: 'Ä',
                    Aring: 'Å',
                    AElig: 'Æ',
                    Ccedil: 'Ç',
                    Egrave: 'È',
                    Eacute: 'É',
                    Ecirc: 'Ê',
                    Euml: 'Ë',
                    Igrave: 'Ì',
                    Iacute: 'Í',
                    Icirc: 'Î',
                    Iuml: 'Ï',
                    ETH: 'Ð',
                    Ntilde: 'Ñ',
                    Ograve: 'Ò',
                    Oacute: 'Ó',
                    Ocirc: 'Ô',
                    Otilde: 'Õ',
                    Ouml: 'Ö',
                    times: '×',
                    Oslash: 'Ø',
                    Ugrave: 'Ù',
                    Uacute: 'Ú',
                    Ucirc: 'Û',
                    Uuml: 'Ü',
                    Yacute: 'Ý',
                    THORN: 'Þ',
                    szlig: 'ß',
                    agrave: 'à',
                    aacute: 'á',
                    acirc: 'â',
                    atilde: 'ã',
                    auml: 'ä',
                    aring: 'å',
                    aelig: 'æ',
                    ccedil: 'ç',
                    egrave: 'è',
                    eacute: 'é',
                    ecirc: 'ê',
                    euml: 'ë',
                    igrave: 'ì',
                    iacute: 'í',
                    icirc: 'î',
                    iuml: 'ï',
                    eth: 'ð',
                    ntilde: 'ñ',
                    ograve: 'ò',
                    oacute: 'ó',
                    ocirc: 'ô',
                    otilde: 'õ',
                    ouml: 'ö',
                    divide: '÷',
                    oslash: 'ø',
                    ugrave: 'ù',
                    uacute: 'ú',
                    ucirc: 'û',
                    uuml: 'ü',
                    yacute: 'ý',
                    thorn: 'þ',
                    yuml: 'ÿ',
                    fnof: 'ƒ',
                    Alpha: 'Α',
                    Beta: 'Β',
                    Gamma: 'Γ',
                    Delta: 'Δ',
                    Epsilon: 'Ε',
                    Zeta: 'Ζ',
                    Eta: 'Η',
                    Theta: 'Θ',
                    Iota: 'Ι',
                    Kappa: 'Κ',
                    Lambda: 'Λ',
                    Mu: 'Μ',
                    Nu: 'Ν',
                    Xi: 'Ξ',
                    Omicron: 'Ο',
                    Pi: 'Π',
                    Rho: 'Ρ',
                    Sigma: 'Σ',
                    Tau: 'Τ',
                    Upsilon: 'Υ',
                    Phi: 'Φ',
                    Chi: 'Χ',
                    Psi: 'Ψ',
                    Omega: 'Ω',
                    alpha: 'α',
                    beta: 'β',
                    gamma: 'γ',
                    delta: 'δ',
                    epsilon: 'ε',
                    zeta: 'ζ',
                    eta: 'η',
                    theta: 'θ',
                    iota: 'ι',
                    kappa: 'κ',
                    lambda: 'λ',
                    mu: 'μ',
                    nu: 'ν',
                    xi: 'ξ',
                    omicron: 'ο',
                    pi: 'π',
                    rho: 'ρ',
                    sigmaf: 'ς',
                    sigma: 'σ',
                    tau: 'τ',
                    upsilon: 'υ',
                    phi: 'φ',
                    chi: 'χ',
                    psi: 'ψ',
                    omega: 'ω',
                    thetasym: 'ϑ',
                    upsih: 'ϒ',
                    piv: 'ϖ',
                    bull: '•',
                    hellip: '…',
                    prime: '′',
                    Prime: '″',
                    oline: '‾',
                    frasl: '⁄',
                    weierp: '℘',
                    image: 'ℑ',
                    real: 'ℜ',
                    trade: '™',
                    alefsym: 'ℵ',
                    larr: '←',
                    uarr: '↑',
                    rarr: '→',
                    darr: '↓',
                    harr: '↔',
                    crarr: '↵',
                    lArr: '⇐',
                    uArr: '⇑',
                    rArr: '⇒',
                    dArr: '⇓',
                    hArr: '⇔',
                    forall: '∀',
                    part: '∂',
                    exist: '∃',
                    empty: '∅',
                    nabla: '∇',
                    isin: '∈',
                    notin: '∉',
                    ni: '∋',
                    prod: '∏',
                    sum: '∑',
                    minus: '−',
                    lowast: '∗',
                    radic: '√',
                    prop: '∝',
                    infin: '∞',
                    ang: '∠',
                    and: '∧',
                    or: '∨',
                    cap: '∩',
                    cup: '∪',
                    int: '∫',
                    there4: '∴',
                    sim: '∼',
                    cong: '≅',
                    asymp: '≈',
                    ne: '≠',
                    equiv: '≡',
                    le: '≤',
                    ge: '≥',
                    sub: '⊂',
                    sup: '⊃',
                    nsub: '⊄',
                    sube: '⊆',
                    supe: '⊇',
                    oplus: '⊕',
                    otimes: '⊗',
                    perp: '⊥',
                    sdot: '⋅',
                    lceil: '⌈',
                    rceil: '⌉',
                    lfloor: '⌊',
                    rfloor: '⌋',
                    lang: '〈',
                    rang: '〉',
                    loz: '◊',
                    spades: '♠',
                    clubs: '♣',
                    hearts: '♥',
                    diams: '♦',
                    quot: '"',
                    amp: '&',
                    lt: '<',
                    gt: '>',
                    OElig: 'Œ',
                    oelig: 'œ',
                    Scaron: 'Š',
                    scaron: 'š',
                    Yuml: 'Ÿ',
                    circ: 'ˆ',
                    tilde: '˜',
                    ensp: ' ',
                    emsp: ' ',
                    thinsp: ' ',
                    zwnj: '‌',
                    zwj: '‍',
                    lrm: '‎',
                    rlm: '‏',
                    ndash: '–',
                    mdash: '—',
                    lsquo: '‘',
                    rsquo: '’',
                    sbquo: '‚',
                    ldquo: '“',
                    rdquo: '”',
                    bdquo: '„',
                    dagger: '†',
                    Dagger: '‡',
                    permil: '‰',
                    lsaquo: '‹',
                    rsaquo: '›',
                    euro: '€'
                };

                /**
                 * List of legacy (that don’t need a trailing `;`) named references which could,
                 * depending on what follows them, turn into a different meaning
                 *
                 * @type {Array<string>}
                 */
                var dangerous = ['cent', 'copy', 'divide', 'gt', 'lt', 'not', 'para', 'times'];
                var own$1 = {}.hasOwnProperty;

                /**
                 * `characterEntitiesHtml4` but inverted.
                 *
                 * @type {Record<string, string>}
                 */
                var characters = {};

                /** @type {string} */
                var key;
                for (key in characterEntitiesHtml4) {
                    if (own$1.call(characterEntitiesHtml4, key)) {
                        characters[characterEntitiesHtml4[key]] = key;
                    }
                }
                var notAlphanumericRegex = /[^\dA-Za-z]/;

                /**
                 * Configurable ways to encode characters as named references.
                 *
                 * @param {number} code
                 * @param {number} next
                 * @param {boolean|undefined} omit
                 * @param {boolean|undefined} attribute
                 * @returns {string}
                 */
                function toNamed(code, next, omit, attribute) {
                    var character = String.fromCharCode(code);
                    if (own$1.call(characters, character)) {
                        var name = characters[character];
                        var value = '&' + name;
                        if (omit && characterEntitiesLegacy.includes(name) && !dangerous.includes(name) && (!attribute || next && next !== 61 /* `=` */ && notAlphanumericRegex.test(String.fromCharCode(next)))) {
                            return value;
                        }
                        return value + ';';
                    }
                    return '';
                }

                /**
                 * @typedef FormatSmartOptions
                 * @property {boolean} [useNamedReferences=false]
                 *   Prefer named character references (`&amp;`) where possible.
                 * @property {boolean} [useShortestReferences=false]
                 *   Prefer the shortest possible reference, if that results in less bytes.
                 *   **Note**: `useNamedReferences` can be omitted when using `useShortestReferences`.
                 * @property {boolean} [omitOptionalSemicolons=false]
                 *   Whether to omit semicolons when possible.
                 *   **Note**: This creates what HTML calls “parse errors” but is otherwise still valid HTML — don’t use this except when building a minifier.
                 *   Omitting semicolons is possible for certain named and numeric references in some cases.
                 * @property {boolean} [attribute=false]
                 *   Create character references which don’t fail in attributes.
                 *   **Note**: `attribute` only applies when operating dangerously with
                 *   `omitOptionalSemicolons: true`.
                 */

                /**
                 * Configurable ways to encode a character yielding pretty or small results.
                 *
                 * @param {number} code
                 * @param {number} next
                 * @param {FormatSmartOptions} options
                 * @returns {string}
                 */
                function formatSmart(code, next, options) {
                    var numeric = toHexadecimal(code, next, options.omitOptionalSemicolons);
                    /** @type {string|undefined} */
                    var named;
                    if (options.useNamedReferences || options.useShortestReferences) {
                        named = toNamed(code, next, options.omitOptionalSemicolons, options.attribute);
                    }

                    // Use the shortest numeric reference when requested.
                    // A simple algorithm would use decimal for all code points under 100, as
                    // those are shorter than hexadecimal:
                    //
                    // * `&#99;` vs `&#x63;` (decimal shorter)
                    // * `&#100;` vs `&#x64;` (equal)
                    //
                    // However, because we take `next` into consideration when `omit` is used,
                    // And it would be possible that decimals are shorter on bigger values as
                    // well if `next` is hexadecimal but not decimal, we instead compare both.
                    if ((options.useShortestReferences || !named) && options.useShortestReferences) {
                        var decimal = toDecimal(code, next, options.omitOptionalSemicolons);
                        if (decimal.length < numeric.length) {
                            numeric = decimal;
                        }
                    }
                    return named && (!options.useShortestReferences || named.length < numeric.length) ? named : numeric;
                }

                /**
                 * @typedef {import('./core.js').CoreOptions & import('./util/format-smart.js').FormatSmartOptions} Options
                 * @typedef {import('./core.js').CoreOptions} LightOptions
                 */

                /**
                 * Encode special characters in `value`.
                 *
                 * @param {string} value
                 *   Value to encode.
                 * @param {Options} [options]
                 *   Configuration.
                 * @returns {string}
                 *   Encoded value.
                 */
                function stringifyEntities(value, options) {
                    return core(value, Object.assign({
                        format: formatSmart
                    }, options));
                }

                /**
                 * @import {Comment, Parents} from 'hast'
                 * @import {State} from '../index.js'
                 */

                var htmlCommentRegex = /^>|^->|<!--|-->|--!>|<!-$/g;

                // Declare arrays as variables so it can be cached by `stringifyEntities`
                var bogusCommentEntitySubset = ['>'];
                var commentEntitySubset = ['<', '>'];

                /**
                 * Serialize a comment.
                 *
                 * @param {Comment} node
                 *   Node to handle.
                 * @param {number | undefined} _1
                 *   Index of `node` in `parent.
                 * @param {Parents | undefined} _2
                 *   Parent of `node`.
                 * @param {State} state
                 *   Info passed around about the current state.
                 * @returns {string}
                 *   Serialized node.
                 */
                function comment(node, _1, _2, state) {
                    // See: <https://html.spec.whatwg.org/multipage/syntax.html#comments>
                    return state.settings.bogusComments ? '<?' + stringifyEntities(node.value, Object.assign({}, state.settings.characterReferences, {
                        subset: bogusCommentEntitySubset
                    })) + '>' : '<!--' + node.value.replace(htmlCommentRegex, encode) + '-->';

                    /**
                     * @param {string} $0
                     */
                    function encode($0) {
                        return stringifyEntities($0, Object.assign({}, state.settings.characterReferences, {
                            subset: commentEntitySubset
                        }));
                    }
                }

                /**
                 * @import {Doctype, Parents} from 'hast'
                 * @import {State} from '../index.js'
                 */

                /**
                 * Serialize a doctype.
                 *
                 * @param {Doctype} _1
                 *   Node to handle.
                 * @param {number | undefined} _2
                 *   Index of `node` in `parent.
                 * @param {Parents | undefined} _3
                 *   Parent of `node`.
                 * @param {State} state
                 *   Info passed around about the current state.
                 * @returns {string}
                 *   Serialized node.
                 */
                function doctype(_1, _2, _3, state) {
                    return '<!' + (state.settings.upperDoctype ? 'DOCTYPE' : 'doctype') + (state.settings.tightDoctype ? '' : ' ') + 'html>';
                }

                /**
                 * Count how often a character (or substring) is used in a string.
                 *
                 * @param {string} value
                 *   Value to search in.
                 * @param {string} character
                 *   Character (or substring) to look for.
                 * @return {number}
                 *   Number of times `character` occurred in `value`.
                 */
                function ccount(value, character) {
                    var source = String(value);
                    if (typeof character !== 'string') {
                        throw new TypeError('Expected character');
                    }
                    var count = 0;
                    var index = source.indexOf(character);
                    while (index !== -1) {
                        count++;
                        index = source.indexOf(character, index + character.length);
                    }
                    return count;
                }

                /**
                 * @typedef Options
                 *   Configuration for `stringify`.
                 * @property {boolean} [padLeft=true]
                 *   Whether to pad a space before a token.
                 * @property {boolean} [padRight=false]
                 *   Whether to pad a space after a token.
                 */

                /**
                 * Serialize an array of strings or numbers to comma-separated tokens.
                 *
                 * @param {Array<string|number>} values
                 *   List of tokens.
                 * @param {Options} [options]
                 *   Configuration for `stringify` (optional).
                 * @returns {string}
                 *   Comma-separated tokens.
                 */
                function stringify$2(values, options) {
                    var settings = options || {};

                    // Ensure the last empty entry is seen.
                    var input = values[values.length - 1] === '' ? [].concat(_toConsumableArray(values), ['']) : values;
                    return input.join((settings.padRight ? ' ' : '') + ',' + (settings.padLeft === false ? '' : ' ')).trim();
                }

                /**
                 * Parse space-separated tokens to an array of strings.
                 *
                 * @param {string} value
                 *   Space-separated tokens.
                 * @returns {Array<string>}
                 *   List of tokens.
                 */

                /**
                 * Serialize an array of strings as space separated-tokens.
                 *
                 * @param {Array<string|number>} values
                 *   List of tokens.
                 * @returns {string}
                 *   Space-separated tokens.
                 */
                function stringify$1(values) {
                    return values.join(' ').trim();
                }

                /**
                 * @typedef {import('hast').Nodes} Nodes
                 */

                    // HTML whitespace expression.
                    // See <https://infra.spec.whatwg.org/#ascii-whitespace>.
                var re = /[ \t\n\f\r]/g;

                /**
                 * Check if the given value is *inter-element whitespace*.
                 *
                 * @param {Nodes | string} thing
                 *   Thing to check (`Node` or `string`).
                 * @returns {boolean}
                 *   Whether the `value` is inter-element whitespace (`boolean`): consisting of
                 *   zero or more of space, tab (`\t`), line feed (`\n`), carriage return
                 *   (`\r`), or form feed (`\f`); if a node is passed it must be a `Text` node,
                 *   whose `value` field is checked.
                 */
                function whitespace(thing) {
                    return _typeof(thing) === 'object' ? thing.type === 'text' ? empty(thing.value) : false : empty(thing);
                }

                /**
                 * @param {string} value
                 * @returns {boolean}
                 */
                function empty(value) {
                    return value.replace(re, '') === '';
                }

                /**
                 * @import {Parents, RootContent} from 'hast'
                 */

                var siblingAfter = siblings(1);
                var siblingBefore = siblings(-1);

                /** @type {Array<RootContent>} */
                var emptyChildren$1 = [];

                /**
                 * Factory to check siblings in a direction.
                 *
                 * @param {number} increment
                 */
                function siblings(increment) {
                    return sibling;

                    /**
                     * Find applicable siblings in a direction.
                     *
                     * @template {Parents} Parent
                     *   Parent type.
                     * @param {Parent | undefined} parent
                     *   Parent.
                     * @param {number | undefined} index
                     *   Index of child in `parent`.
                     * @param {boolean | undefined} [includeWhitespace=false]
                     *   Whether to include whitespace (default: `false`).
                     * @returns {Parent extends {children: Array<infer Child>} ? Child | undefined : never}
                     *   Child of parent.
                     */
                    function sibling(parent, index, includeWhitespace) {
                        var siblings = parent ? parent.children : emptyChildren$1;
                        var offset = (index || 0) + increment;
                        var next = siblings[offset];
                        if (!includeWhitespace) {
                            while (next && whitespace(next)) {
                                offset += increment;
                                next = siblings[offset];
                            }
                        }

                        // @ts-expect-error: it’s a correct child.
                        return next;
                    }
                }

                /**
                 * @import {Element, Parents} from 'hast'
                 */

                /**
                 * @callback OmitHandle
                 *   Check if a tag can be omitted.
                 * @param {Element} element
                 *   Element to check.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether to omit a tag.
                 *
                 */

                var own = {}.hasOwnProperty;

                /**
                 * Factory to check if a given node can have a tag omitted.
                 *
                 * @param {Record<string, OmitHandle>} handlers
                 *   Omission handlers, where each key is a tag name, and each value is the
                 *   corresponding handler.
                 * @returns {OmitHandle}
                 *   Whether to omit a tag of an element.
                 */
                function omission(handlers) {
                    return omit;

                    /**
                     * Check if a given node can have a tag omitted.
                     *
                     * @type {OmitHandle}
                     */
                    function omit(node, index, parent) {
                        return own.call(handlers, node.tagName) && handlers[node.tagName](node, index, parent);
                    }
                }

                /**
                 * @import {Element, Parents} from 'hast'
                 */

                var closing = omission({
                    body: body$1,
                    caption: headOrColgroupOrCaption,
                    colgroup: headOrColgroupOrCaption,
                    dd: dd,
                    dt: dt,
                    head: headOrColgroupOrCaption,
                    html: html$1,
                    li: li,
                    optgroup: optgroup,
                    option: option,
                    p: p,
                    rp: rubyElement,
                    rt: rubyElement,
                    tbody: tbody$1,
                    td: cells,
                    tfoot: tfoot,
                    th: cells,
                    thead: thead,
                    tr: tr
                });

                /**
                 * Macro for `</head>`, `</colgroup>`, and `</caption>`.
                 *
                 * @param {Element} _
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the closing tag can be omitted.
                 */
                function headOrColgroupOrCaption(_, index, parent) {
                    var next = siblingAfter(parent, index, true);
                    return !next || next.type !== 'comment' && !(next.type === 'text' && whitespace(next.value.charAt(0)));
                }

                /**
                 * Whether to omit `</html>`.
                 *
                 * @param {Element} _
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the closing tag can be omitted.
                 */
                function html$1(_, index, parent) {
                    var next = siblingAfter(parent, index);
                    return !next || next.type !== 'comment';
                }

                /**
                 * Whether to omit `</body>`.
                 *
                 * @param {Element} _
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the closing tag can be omitted.
                 */
                function body$1(_, index, parent) {
                    var next = siblingAfter(parent, index);
                    return !next || next.type !== 'comment';
                }

                /**
                 * Whether to omit `</p>`.
                 *
                 * @param {Element} _
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the closing tag can be omitted.
                 */
                function p(_, index, parent) {
                    var next = siblingAfter(parent, index);
                    return next ? next.type === 'element' && (next.tagName === 'address' || next.tagName === 'article' || next.tagName === 'aside' || next.tagName === 'blockquote' || next.tagName === 'details' || next.tagName === 'div' || next.tagName === 'dl' || next.tagName === 'fieldset' || next.tagName === 'figcaption' || next.tagName === 'figure' || next.tagName === 'footer' || next.tagName === 'form' || next.tagName === 'h1' || next.tagName === 'h2' || next.tagName === 'h3' || next.tagName === 'h4' || next.tagName === 'h5' || next.tagName === 'h6' || next.tagName === 'header' || next.tagName === 'hgroup' || next.tagName === 'hr' || next.tagName === 'main' || next.tagName === 'menu' || next.tagName === 'nav' || next.tagName === 'ol' || next.tagName === 'p' || next.tagName === 'pre' || next.tagName === 'section' || next.tagName === 'table' || next.tagName === 'ul') : !parent ||
                        // Confusing parent.
                        !(parent.type === 'element' && (parent.tagName === 'a' || parent.tagName === 'audio' || parent.tagName === 'del' || parent.tagName === 'ins' || parent.tagName === 'map' || parent.tagName === 'noscript' || parent.tagName === 'video'));
                }

                /**
                 * Whether to omit `</li>`.
                 *
                 * @param {Element} _
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the closing tag can be omitted.
                 */
                function li(_, index, parent) {
                    var next = siblingAfter(parent, index);
                    return !next || next.type === 'element' && next.tagName === 'li';
                }

                /**
                 * Whether to omit `</dt>`.
                 *
                 * @param {Element} _
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the closing tag can be omitted.
                 */
                function dt(_, index, parent) {
                    var next = siblingAfter(parent, index);
                    return Boolean(next && next.type === 'element' && (next.tagName === 'dt' || next.tagName === 'dd'));
                }

                /**
                 * Whether to omit `</dd>`.
                 *
                 * @param {Element} _
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the closing tag can be omitted.
                 */
                function dd(_, index, parent) {
                    var next = siblingAfter(parent, index);
                    return !next || next.type === 'element' && (next.tagName === 'dt' || next.tagName === 'dd');
                }

                /**
                 * Whether to omit `</rt>` or `</rp>`.
                 *
                 * @param {Element} _
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the closing tag can be omitted.
                 */
                function rubyElement(_, index, parent) {
                    var next = siblingAfter(parent, index);
                    return !next || next.type === 'element' && (next.tagName === 'rp' || next.tagName === 'rt');
                }

                /**
                 * Whether to omit `</optgroup>`.
                 *
                 * @param {Element} _
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the closing tag can be omitted.
                 */
                function optgroup(_, index, parent) {
                    var next = siblingAfter(parent, index);
                    return !next || next.type === 'element' && next.tagName === 'optgroup';
                }

                /**
                 * Whether to omit `</option>`.
                 *
                 * @param {Element} _
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the closing tag can be omitted.
                 */
                function option(_, index, parent) {
                    var next = siblingAfter(parent, index);
                    return !next || next.type === 'element' && (next.tagName === 'option' || next.tagName === 'optgroup');
                }

                /**
                 * Whether to omit `</thead>`.
                 *
                 * @param {Element} _
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the closing tag can be omitted.
                 */
                function thead(_, index, parent) {
                    var next = siblingAfter(parent, index);
                    return Boolean(next && next.type === 'element' && (next.tagName === 'tbody' || next.tagName === 'tfoot'));
                }

                /**
                 * Whether to omit `</tbody>`.
                 *
                 * @param {Element} _
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the closing tag can be omitted.
                 */
                function tbody$1(_, index, parent) {
                    var next = siblingAfter(parent, index);
                    return !next || next.type === 'element' && (next.tagName === 'tbody' || next.tagName === 'tfoot');
                }

                /**
                 * Whether to omit `</tfoot>`.
                 *
                 * @param {Element} _
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the closing tag can be omitted.
                 */
                function tfoot(_, index, parent) {
                    return !siblingAfter(parent, index);
                }

                /**
                 * Whether to omit `</tr>`.
                 *
                 * @param {Element} _
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the closing tag can be omitted.
                 */
                function tr(_, index, parent) {
                    var next = siblingAfter(parent, index);
                    return !next || next.type === 'element' && next.tagName === 'tr';
                }

                /**
                 * Whether to omit `</td>` or `</th>`.
                 *
                 * @param {Element} _
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the closing tag can be omitted.
                 */
                function cells(_, index, parent) {
                    var next = siblingAfter(parent, index);
                    return !next || next.type === 'element' && (next.tagName === 'td' || next.tagName === 'th');
                }

                /**
                 * @import {Element, Parents} from 'hast'
                 */

                var opening = omission({
                    body: body,
                    colgroup: colgroup,
                    head: head,
                    html: html,
                    tbody: tbody
                });

                /**
                 * Whether to omit `<html>`.
                 *
                 * @param {Element} node
                 *   Element.
                 * @returns {boolean}
                 *   Whether the opening tag can be omitted.
                 */
                function html(node) {
                    var head = siblingAfter(node, -1);
                    return !head || head.type !== 'comment';
                }

                /**
                 * Whether to omit `<head>`.
                 *
                 * @param {Element} node
                 *   Element.
                 * @returns {boolean}
                 *   Whether the opening tag can be omitted.
                 */
                function head(node) {
                    /** @type {Set<string>} */
                    var seen = new Set();

                    // Whether `srcdoc` or not,
                    // make sure the content model at least doesn’t have too many `base`s/`title`s.
                    var _iterator18 = _createForOfIteratorHelper(node.children),
                        _step18;
                    try {
                        for (_iterator18.s(); !(_step18 = _iterator18.n()).done;) {
                            var _child = _step18.value;
                            if (_child.type === 'element' && (_child.tagName === 'base' || _child.tagName === 'title')) {
                                if (seen.has(_child.tagName)) return false;
                                seen.add(_child.tagName);
                            }
                        }

                        // “May be omitted if the element is empty,
                        // or if the first thing inside the head element is an element.”
                    } catch (err) {
                        _iterator18.e(err);
                    } finally {
                        _iterator18.f();
                    }
                    var child = node.children[0];
                    return !child || child.type === 'element';
                }

                /**
                 * Whether to omit `<body>`.
                 *
                 * @param {Element} node
                 *   Element.
                 * @returns {boolean}
                 *   Whether the opening tag can be omitted.
                 */
                function body(node) {
                    var head = siblingAfter(node, -1, true);
                    return !head || head.type !== 'comment' && !(head.type === 'text' && whitespace(head.value.charAt(0))) && !(head.type === 'element' && (head.tagName === 'meta' || head.tagName === 'link' || head.tagName === 'script' || head.tagName === 'style' || head.tagName === 'template'));
                }

                /**
                 * Whether to omit `<colgroup>`.
                 * The spec describes some logic for the opening tag, but it’s easier to
                 * implement in the closing tag, to the same effect, so we handle it there
                 * instead.
                 *
                 * @param {Element} node
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the opening tag can be omitted.
                 */
                function colgroup(node, index, parent) {
                    var previous = siblingBefore(parent, index);
                    var head = siblingAfter(node, -1, true);

                    // Previous colgroup was already omitted.
                    if (parent && previous && previous.type === 'element' && previous.tagName === 'colgroup' && closing(previous, parent.children.indexOf(previous), parent)) {
                        return false;
                    }
                    return Boolean(head && head.type === 'element' && head.tagName === 'col');
                }

                /**
                 * Whether to omit `<tbody>`.
                 *
                 * @param {Element} node
                 *   Element.
                 * @param {number | undefined} index
                 *   Index of element in parent.
                 * @param {Parents | undefined} parent
                 *   Parent of element.
                 * @returns {boolean}
                 *   Whether the opening tag can be omitted.
                 */
                function tbody(node, index, parent) {
                    var previous = siblingBefore(parent, index);
                    var head = siblingAfter(node, -1);

                    // Previous table section was already omitted.
                    if (parent && previous && previous.type === 'element' && (previous.tagName === 'thead' || previous.tagName === 'tbody') && closing(previous, parent.children.indexOf(previous), parent)) {
                        return false;
                    }
                    return Boolean(head && head.type === 'element' && head.tagName === 'tr');
                }

                /**
                 * @import {Element, Parents, Properties} from 'hast'
                 * @import {State} from '../index.js'
                 */

                /**
                 * Maps of subsets.
                 *
                 * Each value is a matrix of tuples.
                 * The value at `0` causes parse errors, the value at `1` is valid.
                 * Of both, the value at `0` is unsafe, and the value at `1` is safe.
                 *
                 * @type {Record<'double' | 'name' | 'single' | 'unquoted', Array<[Array<string>, Array<string>]>>}
                 */
                var constants = {
                    // See: <https://html.spec.whatwg.org/#attribute-name-state>.
                    name: [['\t\n\f\r &/=>'.split(''), '\t\n\f\r "&\'/=>`'.split('')], ['\0\t\n\f\r "&\'/<=>'.split(''), '\0\t\n\f\r "&\'/<=>`'.split('')]],
                    // See: <https://html.spec.whatwg.org/#attribute-value-(unquoted)-state>.
                    unquoted: [['\t\n\f\r &>'.split(''), '\0\t\n\f\r "&\'<=>`'.split('')], ['\0\t\n\f\r "&\'<=>`'.split(''), '\0\t\n\f\r "&\'<=>`'.split('')]],
                    // See: <https://html.spec.whatwg.org/#attribute-value-(single-quoted)-state>.
                    single: [["&'".split(''), '"&\'`'.split('')], ["\0&'".split(''), '\0"&\'`'.split('')]],
                    // See: <https://html.spec.whatwg.org/#attribute-value-(double-quoted)-state>.
                    double: [['"&'.split(''), '"&\'`'.split('')], ['\0"&'.split(''), '\0"&\'`'.split('')]]
                };

                /**
                 * Serialize an element node.
                 *
                 * @param {Element} node
                 *   Node to handle.
                 * @param {number | undefined} index
                 *   Index of `node` in `parent.
                 * @param {Parents | undefined} parent
                 *   Parent of `node`.
                 * @param {State} state
                 *   Info passed around about the current state.
                 * @returns {string}
                 *   Serialized node.
                 */
                function element(node, index, parent, state) {
                    var schema = state.schema;
                    var omit = schema.space === 'svg' ? false : state.settings.omitOptionalTags;
                    var selfClosing = schema.space === 'svg' ? state.settings.closeEmptyElements : state.settings.voids.includes(node.tagName.toLowerCase());
                    /** @type {Array<string>} */
                    var parts = [];
                    /** @type {string} */
                    var last;
                    if (schema.space === 'html' && node.tagName === 'svg') {
                        state.schema = svg;
                    }
                    var attributes = serializeAttributes(state, node.properties);
                    var content = state.all(schema.space === 'html' && node.tagName === 'template' ? node.content : node);
                    state.schema = schema;

                    // If the node is categorised as void, but it has children, remove the
                    // categorisation.
                    // This enables for example `menuitem`s, which are void in W3C HTML but not
                    // void in WHATWG HTML, to be stringified properly.
                    // Note: `menuitem` has since been removed from the HTML spec, and so is no
                    // longer void.
                    if (content) selfClosing = false;
                    if (attributes || !omit || !opening(node, index, parent)) {
                        parts.push('<', node.tagName, attributes ? ' ' + attributes : '');
                        if (selfClosing && (schema.space === 'svg' || state.settings.closeSelfClosing)) {
                            last = attributes.charAt(attributes.length - 1);
                            if (!state.settings.tightSelfClosing || last === '/' || last && last !== '"' && last !== "'") {
                                parts.push(' ');
                            }
                            parts.push('/');
                        }
                        parts.push('>');
                    }
                    parts.push(content);
                    if (!selfClosing && (!omit || !closing(node, index, parent))) {
                        parts.push('</' + node.tagName + '>');
                    }
                    return parts.join('');
                }

                /**
                 * @param {State} state
                 * @param {Properties | null | undefined} properties
                 * @returns {string}
                 */
                function serializeAttributes(state, properties) {
                    /** @type {Array<string>} */
                    var values = [];
                    var index = -1;
                    /** @type {string} */
                    var key;
                    if (properties) {
                        for (key in properties) {
                            if (properties[key] !== null && properties[key] !== undefined) {
                                var value = serializeAttribute(state, key, properties[key]);
                                if (value) values.push(value);
                            }
                        }
                    }
                    while (++index < values.length) {
                        var last = state.settings.tightAttributes ? values[index].charAt(values[index].length - 1) : undefined;

                        // In tight mode, don’t add a space after quoted attributes.
                        if (index !== values.length - 1 && last !== '"' && last !== "'") {
                            values[index] += ' ';
                        }
                    }
                    return values.join('');
                }

                /**
                 * @param {State} state
                 * @param {string} key
                 * @param {Properties[keyof Properties]} value
                 * @returns {string}
                 */
                function serializeAttribute(state, key, value) {
                    var info = find(state.schema, key);
                    var x = state.settings.allowParseErrors && state.schema.space === 'html' ? 0 : 1;
                    var y = state.settings.allowDangerousCharacters ? 0 : 1;
                    var quote = state.quote;
                    /** @type {string | undefined} */
                    var result;
                    if (info.overloadedBoolean && (value === info.attribute || value === '')) {
                        value = true;
                    } else if ((info.boolean || info.overloadedBoolean) && (typeof value !== 'string' || value === info.attribute || value === '')) {
                        value = Boolean(value);
                    }
                    if (value === null || value === undefined || value === false || typeof value === 'number' && Number.isNaN(value)) {
                        return '';
                    }
                    var name = stringifyEntities(info.attribute, Object.assign({}, state.settings.characterReferences, {
                        // Always encode without parse errors in non-HTML.
                        subset: constants.name[x][y]
                    }));

                    // No value.
                    // There is currently only one boolean property in SVG: `[download]` on
                    // `<a>`.
                    // This property does not seem to work in browsers (Firefox, Safari, Chrome),
                    // so I can’t test if dropping the value works.
                    // But I assume that it should:
                    //
                    // ```html
                    // <!doctype html>
                    // <svg viewBox="0 0 100 100">
                    //   <a href=https://example.com download>
                    //     <circle cx=50 cy=40 r=35 />
                    //   </a>
                    // </svg>
                    // ```
                    //
                    // See: <https://github.com/wooorm/property-information/blob/main/lib/svg.js>
                    if (value === true) return name;

                    // `spaces` doesn’t accept a second argument, but it’s given here just to
                    // keep the code cleaner.
                    value = Array.isArray(value) ? (info.commaSeparated ? stringify$2 : stringify$1)(value, {
                        padLeft: !state.settings.tightCommaSeparatedLists
                    }) : String(value);
                    if (state.settings.collapseEmptyAttributes && !value) return name;

                    // Check unquoted value.
                    if (state.settings.preferUnquoted) {
                        result = stringifyEntities(value, Object.assign({}, state.settings.characterReferences, {
                            attribute: true,
                            subset: constants.unquoted[x][y]
                        }));
                    }

                    // If we don’t want unquoted, or if `value` contains character references when
                    // unquoted…
                    if (result !== value) {
                        // If the alternative is less common than `quote`, switch.
                        if (state.settings.quoteSmart && ccount(value, quote) > ccount(value, state.alternative)) {
                            quote = state.alternative;
                        }
                        result = quote + stringifyEntities(value, Object.assign({}, state.settings.characterReferences, {
                            // Always encode without parse errors in non-HTML.
                            subset: (quote === "'" ? constants.single : constants.double)[x][y],
                            attribute: true
                        })) + quote;
                    }

                    // Don’t add a `=` for unquoted empties.
                    return name + (result ? '=' + result : result);
                }

                /**
                 * @import {Parents, Text} from 'hast'
                 * @import {Raw} from 'mdast-util-to-hast'
                 * @import {State} from '../index.js'
                 */

                    // Declare array as variable so it can be cached by `stringifyEntities`
                var textEntitySubset = ['<', '&'];

                /**
                 * Serialize a text node.
                 *
                 * @param {Raw | Text} node
                 *   Node to handle.
                 * @param {number | undefined} _
                 *   Index of `node` in `parent.
                 * @param {Parents | undefined} parent
                 *   Parent of `node`.
                 * @param {State} state
                 *   Info passed around about the current state.
                 * @returns {string}
                 *   Serialized node.
                 */
                function text(node, _, parent, state) {
                    // Check if content of `node` should be escaped.
                    return parent && parent.type === 'element' && (parent.tagName === 'script' || parent.tagName === 'style') ? node.value : stringifyEntities(node.value, Object.assign({}, state.settings.characterReferences, {
                        subset: textEntitySubset
                    }));
                }

                /**
                 * @import {Parents} from 'hast'
                 * @import {Raw} from 'mdast-util-to-hast'
                 * @import {State} from '../index.js'
                 */

                /**
                 * Serialize a raw node.
                 *
                 * @param {Raw} node
                 *   Node to handle.
                 * @param {number | undefined} index
                 *   Index of `node` in `parent.
                 * @param {Parents | undefined} parent
                 *   Parent of `node`.
                 * @param {State} state
                 *   Info passed around about the current state.
                 * @returns {string}
                 *   Serialized node.
                 */
                function raw(node, index, parent, state) {
                    return state.settings.allowDangerousHtml ? node.value : text(node, index, parent, state);
                }

                /**
                 * @import {Parents, Root} from 'hast'
                 * @import {State} from '../index.js'
                 */

                /**
                 * Serialize a root.
                 *
                 * @param {Root} node
                 *   Node to handle.
                 * @param {number | undefined} _1
                 *   Index of `node` in `parent.
                 * @param {Parents | undefined} _2
                 *   Parent of `node`.
                 * @param {State} state
                 *   Info passed around about the current state.
                 * @returns {string}
                 *   Serialized node.
                 */
                function root(node, _1, _2, state) {
                    return state.all(node);
                }

                /**
                 * @import {Nodes, Parents} from 'hast'
                 * @import {State} from '../index.js'
                 */

                /**
                 * @type {(node: Nodes, index: number | undefined, parent: Parents | undefined, state: State) => string}
                 */
                var handle = zwitch('type', {
                    invalid: invalid,
                    unknown: unknown,
                    handlers: {
                        comment: comment,
                        doctype: doctype,
                        element: element,
                        raw: raw,
                        root: root,
                        text: text
                    }
                });

                /**
                 * Fail when a non-node is found in the tree.
                 *
                 * @param {unknown} node
                 *   Unknown value.
                 * @returns {never}
                 *   Never.
                 */
                function invalid(node) {
                    throw new Error('Expected node, not `' + node + '`');
                }

                /**
                 * Fail when a node with an unknown type is found in the tree.
                 *
                 * @param {unknown} node_
                 *  Unknown node.
                 * @returns {never}
                 *   Never.
                 */
                function unknown(node_) {
                    // `type` is guaranteed by runtime JS.
                    var node = /** @type {Nodes} */node_;
                    throw new Error('Cannot compile unknown node `' + node.type + '`');
                }

                /**
                 * @import {Nodes, Parents, RootContent} from 'hast'
                 * @import {Schema} from 'property-information'
                 * @import {Options as StringifyEntitiesOptions} from 'stringify-entities'
                 */

                /** @type {Options} */
                var emptyOptions = {};

                /** @type {CharacterReferences} */
                var emptyCharacterReferences = {};

                /** @type {Array<never>} */
                var emptyChildren = [];

                /**
                 * Serialize hast as HTML.
                 *
                 * @param {Array<RootContent> | Nodes} tree
                 *   Tree to serialize.
                 * @param {Options | null | undefined} [options]
                 *   Configuration (optional).
                 * @returns {string}
                 *   Serialized HTML.
                 */
                function toHtml(tree, options) {
                    var options_ = emptyOptions;
                    var quote = options_.quote || '"';
                    var alternative = quote === '"' ? "'" : '"';
                    if (quote !== '"' && quote !== "'") {
                        throw new Error('Invalid quote `' + quote + '`, expected `\'` or `"`');
                    }

                    /** @type {State} */
                    var state = {
                        one: one,
                        all: all,
                        settings: {
                            omitOptionalTags: options_.omitOptionalTags || false,
                            allowParseErrors: options_.allowParseErrors || false,
                            allowDangerousCharacters: options_.allowDangerousCharacters || false,
                            quoteSmart: options_.quoteSmart || false,
                            preferUnquoted: options_.preferUnquoted || false,
                            tightAttributes: options_.tightAttributes || false,
                            upperDoctype: options_.upperDoctype || false,
                            tightDoctype: options_.tightDoctype || false,
                            bogusComments: options_.bogusComments || false,
                            tightCommaSeparatedLists: options_.tightCommaSeparatedLists || false,
                            tightSelfClosing: options_.tightSelfClosing || false,
                            collapseEmptyAttributes: options_.collapseEmptyAttributes || false,
                            allowDangerousHtml: options_.allowDangerousHtml || false,
                            voids: options_.voids || htmlVoidElements,
                            characterReferences: options_.characterReferences || emptyCharacterReferences,
                            closeSelfClosing: options_.closeSelfClosing || false,
                            closeEmptyElements: options_.closeEmptyElements || false
                        },
                        schema: options_.space === 'svg' ? svg : html$2,
                        quote: quote,
                        alternative: alternative
                    };
                    return state.one(Array.isArray(tree) ? {
                        type: 'root',
                        children: tree
                    } : tree, undefined, undefined);
                }

                /**
                 * Serialize a node.
                 *
                 * @this {State}
                 *   Info passed around about the current state.
                 * @param {Nodes} node
                 *   Node to handle.
                 * @param {number | undefined} index
                 *   Index of `node` in `parent.
                 * @param {Parents | undefined} parent
                 *   Parent of `node`.
                 * @returns {string}
                 *   Serialized node.
                 */
                function one(node, index, parent) {
                    return handle(node, index, parent, this);
                }

                /**
                 * Serialize all children of `parent`.
                 *
                 * @this {State}
                 *   Info passed around about the current state.
                 * @param {Parents | undefined} parent
                 *   Parent whose children to serialize.
                 * @returns {string}
                 */
                function all(parent) {
                    /** @type {Array<string>} */
                    var results = [];
                    var children = parent && parent.children || emptyChildren;
                    var index = -1;
                    while (++index < children.length) {
                        results[index] = this.one(children[index], index, parent);
                    }
                    return results.join('');
                }

                function toArray(x) {
                    return Array.isArray(x) ? x : [x];
                }

                function splitLines(code) {
                    var preserveEnding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
                    var parts = code.split(/(\r?\n)/g);
                    var index = 0;
                    var lines = [];
                    for (var i = 0; i < parts.length; i += 2) {
                        var _parts;
                        var line = preserveEnding ? parts[i] + (parts[i + 1] || "") : parts[i];
                        lines.push([line, index]);
                        index += parts[i].length;
                        index += ((_parts = parts[i + 1]) === null || _parts === void 0 ? void 0 : _parts.length) || 0;
                    }
                    return lines;
                }

                function isPlainLang(lang) {
                    return !lang || ["plaintext", "txt", "text", "plain"].includes(lang);
                }

                function isSpecialLang(lang) {
                    return lang === "ansi" || isPlainLang(lang);
                }

                function isNoneTheme(theme) {
                    return theme === "none";
                }

                function isSpecialTheme(theme) {
                    return isNoneTheme(theme);
                }

                function addClassToHast(node, className) {
                    var _node$properties;
                    if (!className) return node;
                    node.properties || (node.properties = {});
                    (_node$properties = node.properties).class || (_node$properties.class = []);
                    if (typeof node.properties.class === "string") node.properties.class = node.properties.class.split(/\s+/g);
                    if (!Array.isArray(node.properties.class)) node.properties.class = [];
                    var targets = Array.isArray(className) ? className : className.split(/\s+/g);
                    var _iterator19 = _createForOfIteratorHelper(targets),
                        _step19;
                    try {
                        for (_iterator19.s(); !(_step19 = _iterator19.n()).done;) {
                            var c = _step19.value;
                            if (c && !node.properties.class.includes(c)) node.properties.class.push(c);
                        }
                    } catch (err) {
                        _iterator19.e(err);
                    } finally {
                        _iterator19.f();
                    }
                    return node;
                }

                function splitToken(token, offsets) {
                    var lastOffset = 0;
                    var tokens = [];
                    var _iterator20 = _createForOfIteratorHelper(offsets),
                        _step20;
                    try {
                        for (_iterator20.s(); !(_step20 = _iterator20.n()).done;) {
                            var offset = _step20.value;
                            if (offset > lastOffset) {
                                tokens.push(_objectSpread(_objectSpread({}, token), {}, {
                                    content: token.content.slice(lastOffset, offset),
                                    offset: token.offset + lastOffset
                                }));
                            }
                            lastOffset = offset;
                        }
                    } catch (err) {
                        _iterator20.e(err);
                    } finally {
                        _iterator20.f();
                    }
                    if (lastOffset < token.content.length) {
                        tokens.push(_objectSpread(_objectSpread({}, token), {}, {
                            content: token.content.slice(lastOffset),
                            offset: token.offset + lastOffset
                        }));
                    }
                    return tokens;
                }

                function splitTokens(tokens, breakpoints) {
                    var sorted = Array.from(breakpoints instanceof Set ? breakpoints : new Set(breakpoints)).sort(function (a, b) {
                        return a - b;
                    });
                    if (!sorted.length) return tokens;
                    return tokens.map(function (line) {
                        return line.flatMap(function (token) {
                            var breakpointsInToken = sorted.filter(function (i) {
                                return token.offset < i && i < token.offset + token.content.length;
                            }).map(function (i) {
                                return i - token.offset;
                            }).sort(function (a, b) {
                                return a - b;
                            });
                            if (!breakpointsInToken.length) return token;
                            return splitToken(token, breakpointsInToken);
                        });
                    });
                }

                function normalizeGetter(_x5) {
                    return _normalizeGetter.apply(this, arguments);
                }

                function _normalizeGetter() {
                    _normalizeGetter = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(p) {
                        return _regeneratorRuntime().wrap(function _callee10$(_context10) {
                            while (1) switch (_context10.prev = _context10.next) {
                                case 0:
                                    return _context10.abrupt("return", Promise.resolve(typeof p === "function" ? p() : p).then(function (r) {
                                        return r.default || r;
                                    }));
                                case 1:
                                case "end":
                                    return _context10.stop();
                            }
                        }, _callee10);
                    }));
                    return _normalizeGetter.apply(this, arguments);
                }

                function resolveColorReplacements(theme, options) {
                    var replacements = typeof theme === "string" ? {} : _objectSpread({}, theme.colorReplacements);
                    var themeName = typeof theme === "string" ? theme : theme.name;
                    for (var _i3 = 0, _Object$entries = Object.entries((options === null || options === void 0 ? void 0 : options.colorReplacements) || {}); _i3 < _Object$entries.length; _i3++) {
                        var _Object$entries$_i = _slicedToArray(_Object$entries[_i3], 2),
                            _key5 = _Object$entries$_i[0],
                            value = _Object$entries$_i[1];
                        if (typeof value === "string") replacements[_key5] = value; else if (_key5 === themeName) Object.assign(replacements, value);
                    }
                    return replacements;
                }

                function applyColorReplacements(color, replacements) {
                    if (!color) return color;
                    return (replacements === null || replacements === void 0 ? void 0 : replacements[color === null || color === void 0 ? void 0 : color.toLowerCase()]) || color;
                }

                function getTokenStyleObject(token) {
                    var styles = {};
                    if (token.color) styles.color = token.color;
                    if (token.bgColor) styles["background-color"] = token.bgColor;
                    if (token.fontStyle) {
                        if (token.fontStyle & FontStyle.Italic) styles["font-style"] = "italic";
                        if (token.fontStyle & FontStyle.Bold) styles["font-weight"] = "bold";
                        if (token.fontStyle & FontStyle.Underline) styles["text-decoration"] = "underline";
                    }
                    return styles;
                }

                function stringifyTokenStyle(token) {
                    if (typeof token === "string") return token;
                    return Object.entries(token).map(function (_ref5) {
                        var _ref6 = _slicedToArray(_ref5, 2),
                            key = _ref6[0],
                            value = _ref6[1];
                        return "".concat(key, ":").concat(value);
                    }).join(";");
                }

                function createPositionConverter(code) {
                    var lines = splitLines(code, true).map(function (_ref7) {
                        var _ref8 = _slicedToArray(_ref7, 1),
                            line = _ref8[0];
                        return line;
                    });

                    function indexToPos(index) {
                        if (index === code.length) {
                            return {
                                line: lines.length - 1,
                                character: lines[lines.length - 1].length
                            };
                        }
                        var character = index;
                        var line = 0;
                        var _iterator21 = _createForOfIteratorHelper(lines),
                            _step21;
                        try {
                            for (_iterator21.s(); !(_step21 = _iterator21.n()).done;) {
                                var lineText = _step21.value;
                                if (character < lineText.length) break;
                                character -= lineText.length;
                                line++;
                            }
                        } catch (err) {
                            _iterator21.e(err);
                        } finally {
                            _iterator21.f();
                        }
                        return {
                            line: line,
                            character: character
                        };
                    }

                    function posToIndex(line, character) {
                        var index = 0;
                        for (var i = 0; i < line; i++) index += lines[i].length;
                        index += character;
                        return index;
                    }

                    return {
                        lines: lines,
                        indexToPos: indexToPos,
                        posToIndex: posToIndex
                    };
                }

                var ShikiError = /*#__PURE__*/function (_Error3) {
                    function ShikiError(message) {
                        var _this14;
                        _classCallCheck(this, ShikiError);
                        _this14 = _callSuper(this, ShikiError, [message]);
                        _this14.name = "ShikiError";
                        return _this14;
                    }

                    _inherits(ShikiError, _Error3);
                    return _createClass(ShikiError);
                }(/*#__PURE__*/_wrapNativeSuper(Error));
                var _grammarStateMap = /* @__PURE__ */new WeakMap();

                function setLastGrammarStateToMap(keys, state) {
                    _grammarStateMap.set(keys, state);
                }

                function getLastGrammarStateFromMap(keys) {
                    return _grammarStateMap.get(keys);
                }

                var GrammarState = /*#__PURE__*/function () {
                    function GrammarState() {
                        _classCallCheck(this, GrammarState);
                        /**
                         * Theme to Stack mapping
                         */
                        _defineProperty(this, "_stacks", {});
                        _defineProperty(this, "lang", void 0);
                        for (var _len4 = arguments.length, args = new Array(_len4), _key6 = 0; _key6 < _len4; _key6++) {
                            args[_key6] = arguments[_key6];
                        }
                        if (args.length === 2) {
                            var stacksMap = args[0],
                                lang = args[1];
                            this.lang = lang;
                            this._stacks = stacksMap;
                        } else {
                            var stack = args[0],
                                _lang2 = args[1],
                                theme = args[2];
                            this.lang = _lang2;
                            this._stacks = _defineProperty({}, theme, stack);
                        }
                    }

                    /**
                     * Get the internal stack object.
                     * @internal
                     */
                    return _createClass(GrammarState, [{
                        key: "themes",
                        get: function get() {
                            return Object.keys(this._stacks);
                        }
                    }, {
                        key: "theme",
                        get: function get() {
                            return this.themes[0];
                        }
                    }, {
                        key: "_stack",
                        get: function get() {
                            return this._stacks[this.theme];
                        }
                        /**
                         * Static method to create a initial grammar state.
                         */
                    }, {
                        key: "getInternalStack",
                        value: function getInternalStack() {
                            var theme = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.theme;
                            return this._stacks[theme];
                        }
                        /**
                         * @deprecated use `getScopes` instead
                         */
                    }, {
                        key: "scopes",
                        get: function get() {
                            warnDeprecated("GrammarState.scopes is deprecated, use GrammarState.getScopes() instead");
                            return _getScopes(this._stacks[this.theme]);
                        }
                    }, {
                        key: "getScopes",
                        value: function getScopes() {
                            var theme = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.theme;
                            return _getScopes(this._stacks[theme]);
                        }
                    }, {
                        key: "toJSON",
                        value: function toJSON() {
                            return {
                                lang: this.lang,
                                theme: this.theme,
                                themes: this.themes,
                                scopes: this.getScopes()
                            };
                        }
                    }], [{
                        key: "initial",
                        value: function initial(lang, themes) {
                            return new GrammarState(Object.fromEntries(toArray(themes).map(function (theme) {
                                return [theme, INITIAL];
                            })), lang);
                        }
                    }]);
                }();

                function _getScopes(stack) {
                    var scopes = [];
                    var visited = /* @__PURE__ */new Set();

                    function pushScope(stack2) {
                        var _stack2$nameScopesLis;
                        if (visited.has(stack2)) return;
                        visited.add(stack2);
                        var name = stack2 === null || stack2 === void 0 || (_stack2$nameScopesLis = stack2.nameScopesList) === null || _stack2$nameScopesLis === void 0 ? void 0 : _stack2$nameScopesLis.scopeName;
                        if (name) scopes.push(name);
                        if (stack2.parent) pushScope(stack2.parent);
                    }

                    pushScope(stack);
                    return scopes;
                }

                function getGrammarStack(state, theme) {
                    if (!(state instanceof GrammarState)) throw new ShikiError("Invalid grammar state");
                    return state.getInternalStack(theme);
                }

                function transformerDecorations() {
                    var map = /* @__PURE__ */new WeakMap();

                    function getContext(shiki) {
                        if (!map.has(shiki.meta)) {
                            var normalizePosition = function normalizePosition(p) {
                                if (typeof p === "number") {
                                    if (p < 0 || p > shiki.source.length) throw new ShikiError("Invalid decoration offset: ".concat(p, ". Code length: ").concat(shiki.source.length));
                                    return _objectSpread(_objectSpread({}, converter.indexToPos(p)), {}, {
                                        offset: p
                                    });
                                } else {
                                    var line = converter.lines[p.line];
                                    if (line === undefined) throw new ShikiError("Invalid decoration position ".concat(JSON.stringify(p), ". Lines length: ").concat(converter.lines.length));
                                    if (p.character < 0 || p.character > line.length) throw new ShikiError("Invalid decoration position ".concat(JSON.stringify(p), ". Line ").concat(p.line, " length: ").concat(line.length));
                                    return _objectSpread(_objectSpread({}, p), {}, {
                                        offset: converter.posToIndex(p.line, p.character)
                                    });
                                }
                            };
                            var converter = createPositionConverter(shiki.source);
                            var _decorations = (shiki.options.decorations || []).map(function (d) {
                                return _objectSpread(_objectSpread({}, d), {}, {
                                    start: normalizePosition(d.start),
                                    end: normalizePosition(d.end)
                                });
                            });
                            verifyIntersections(_decorations);
                            map.set(shiki.meta, {
                                decorations: _decorations,
                                converter: converter,
                                source: shiki.source
                            });
                        }
                        return map.get(shiki.meta);
                    }

                    return {
                        name: "shiki:decorations",
                        tokens: function tokens(_tokens) {
                            var _this$options$decorat;
                            if (!((_this$options$decorat = this.options.decorations) !== null && _this$options$decorat !== void 0 && _this$options$decorat.length)) return;
                            var ctx = getContext(this);
                            var breakpoints = ctx.decorations.flatMap(function (d) {
                                return [d.start.offset, d.end.offset];
                            });
                            var splitted = splitTokens(_tokens, breakpoints);
                            return splitted;
                        },
                        code: function code(codeEl) {
                            var _this$options$decorat2;
                            if (!((_this$options$decorat2 = this.options.decorations) !== null && _this$options$decorat2 !== void 0 && _this$options$decorat2.length)) return;
                            var ctx = getContext(this);
                            var lines = Array.from(codeEl.children).filter(function (i) {
                                return i.type === "element" && i.tagName === "span";
                            });
                            if (lines.length !== ctx.converter.lines.length) throw new ShikiError("Number of lines in code element (".concat(lines.length, ") does not match the number of lines in the source (").concat(ctx.converter.lines.length, "). Failed to apply decorations."));

                            function applyLineSection(line, start, end, decoration) {
                                var lineEl = lines[line];
                                var text = "";
                                var startIndex = -1;
                                var endIndex = -1;
                                if (start === 0) startIndex = 0;
                                if (end === 0) endIndex = 0;
                                if (end === Number.POSITIVE_INFINITY) endIndex = lineEl.children.length;
                                if (startIndex === -1 || endIndex === -1) {
                                    for (var i = 0; i < lineEl.children.length; i++) {
                                        text += stringify(lineEl.children[i]);
                                        if (startIndex === -1 && text.length === start) startIndex = i + 1;
                                        if (endIndex === -1 && text.length === end) endIndex = i + 1;
                                    }
                                }
                                if (startIndex === -1) throw new ShikiError("Failed to find start index for decoration ".concat(JSON.stringify(decoration.start)));
                                if (endIndex === -1) throw new ShikiError("Failed to find end index for decoration ".concat(JSON.stringify(decoration.end)));
                                var children = lineEl.children.slice(startIndex, endIndex);
                                if (!decoration.alwaysWrap && children.length === lineEl.children.length) {
                                    applyDecoration(lineEl, decoration, "line");
                                } else if (!decoration.alwaysWrap && children.length === 1 && children[0].type === "element") {
                                    applyDecoration(children[0], decoration, "token");
                                } else {
                                    var wrapper = {
                                        type: "element",
                                        tagName: "span",
                                        properties: {},
                                        children: children
                                    };
                                    applyDecoration(wrapper, decoration, "wrapper");
                                    lineEl.children.splice(startIndex, children.length, wrapper);
                                }
                            }

                            function applyLine(line, decoration) {
                                lines[line] = applyDecoration(lines[line], decoration, "line");
                            }

                            function applyDecoration(el, decoration, type) {
                                var _decoration$propertie;
                                var properties = decoration.properties || {};
                                var transform = decoration.transform || function (i) {
                                    return i;
                                };
                                el.tagName = decoration.tagName || "span";
                                el.properties = _objectSpread(_objectSpread(_objectSpread({}, el.properties), properties), {}, {
                                    class: el.properties.class
                                });
                                if ((_decoration$propertie = decoration.properties) !== null && _decoration$propertie !== void 0 && _decoration$propertie.class) addClassToHast(el, decoration.properties.class);
                                el = transform(el, type) || el;
                                return el;
                            }

                            var lineApplies = [];
                            var sorted = ctx.decorations.sort(function (a, b) {
                                return b.start.offset - a.start.offset || a.end.offset - b.end.offset;
                            });
                            var _iterator22 = _createForOfIteratorHelper(sorted),
                                _step22;
                            try {
                                var _loop = function _loop() {
                                    var decoration = _step22.value;
                                    var start = decoration.start,
                                        end = decoration.end;
                                    if (start.line === end.line) {
                                        applyLineSection(start.line, start.character, end.character, decoration);
                                    } else if (start.line < end.line) {
                                        applyLineSection(start.line, start.character, Number.POSITIVE_INFINITY, decoration);
                                        var _loop2 = function _loop2(i) {
                                            lineApplies.unshift(function () {
                                                return applyLine(i, decoration);
                                            });
                                        };
                                        for (var i = start.line + 1; i < end.line; i++) {
                                            _loop2(i);
                                        }
                                        applyLineSection(end.line, 0, end.character, decoration);
                                    }
                                };
                                for (_iterator22.s(); !(_step22 = _iterator22.n()).done;) {
                                    _loop();
                                }
                            } catch (err) {
                                _iterator22.e(err);
                            } finally {
                                _iterator22.f();
                            }
                            lineApplies.forEach(function (i) {
                                return i();
                            });
                        }
                    };
                }

                function verifyIntersections(items) {
                    for (var i = 0; i < items.length; i++) {
                        var foo = items[i];
                        if (foo.start.offset > foo.end.offset) throw new ShikiError("Invalid decoration range: ".concat(JSON.stringify(foo.start), " - ").concat(JSON.stringify(foo.end)));
                        for (var j = i + 1; j < items.length; j++) {
                            var bar = items[j];
                            var isFooHasBarStart = foo.start.offset <= bar.start.offset && bar.start.offset < foo.end.offset;
                            var isFooHasBarEnd = foo.start.offset < bar.end.offset && bar.end.offset <= foo.end.offset;
                            var isBarHasFooStart = bar.start.offset <= foo.start.offset && foo.start.offset < bar.end.offset;
                            var isBarHasFooEnd = bar.start.offset < foo.end.offset && foo.end.offset <= bar.end.offset;
                            if (isFooHasBarStart || isFooHasBarEnd || isBarHasFooStart || isBarHasFooEnd) {
                                if (isFooHasBarStart && isFooHasBarEnd) continue;
                                if (isBarHasFooStart && isBarHasFooEnd) continue;
                                throw new ShikiError("Decorations ".concat(JSON.stringify(foo.start), " and ").concat(JSON.stringify(bar.start), " intersect."));
                            }
                        }
                    }
                }

                function stringify(el) {
                    if (el.type === "text") return el.value;
                    if (el.type === "element") return el.children.map(stringify).join("");
                    return "";
                }

                var builtInTransformers = [/* @__PURE__ */transformerDecorations()];

                function getTransformers(options) {
                    return [].concat(_toConsumableArray(options.transformers || []), builtInTransformers);
                }

                // src/colors.ts
                var namedColors = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "brightBlack", "brightRed", "brightGreen", "brightYellow", "brightBlue", "brightMagenta", "brightCyan", "brightWhite"];

                // src/decorations.ts
                var decorations = {
                    1: "bold",
                    2: "dim",
                    3: "italic",
                    4: "underline",
                    7: "reverse",
                    9: "strikethrough"
                };

                // src/parser.ts
                function findSequence(value, position) {
                    var nextEscape = value.indexOf("\x1B[", position);
                    if (nextEscape !== -1) {
                        var nextClose = value.indexOf("m", nextEscape);
                        return {
                            sequence: value.substring(nextEscape + 2, nextClose).split(";"),
                            startPosition: nextEscape,
                            position: nextClose + 1
                        };
                    }
                    return {
                        position: value.length
                    };
                }

                function parseColor(sequence, index) {
                    var offset = 1;
                    var colorMode = sequence[index + offset++];
                    var color;
                    if (colorMode === "2") {
                        var rgb = [sequence[index + offset++], sequence[index + offset++], sequence[index + offset]].map(function (x) {
                            return Number.parseInt(x);
                        });
                        if (rgb.length === 3 && !rgb.some(function (x) {
                            return Number.isNaN(x);
                        })) {
                            color = {
                                type: "rgb",
                                rgb: rgb
                            };
                        }
                    } else if (colorMode === "5") {
                        var colorIndex = Number.parseInt(sequence[index + offset]);
                        if (!Number.isNaN(colorIndex)) {
                            color = {
                                type: "table",
                                index: Number(colorIndex)
                            };
                        }
                    }
                    return [offset, color];
                }

                function parseSequence(sequence) {
                    var commands = [];
                    for (var i = 0; i < sequence.length; i++) {
                        var code = sequence[i];
                        var codeInt = Number.parseInt(code);
                        if (Number.isNaN(codeInt)) continue;
                        if (codeInt === 0) {
                            commands.push({
                                type: "resetAll"
                            });
                        } else if (codeInt <= 9) {
                            var decoration = decorations[codeInt];
                            if (decoration) {
                                commands.push({
                                    type: "setDecoration",
                                    value: decorations[codeInt]
                                });
                            }
                        } else if (codeInt <= 29) {
                            var _decoration = decorations[codeInt - 20];
                            if (_decoration) {
                                commands.push({
                                    type: "resetDecoration",
                                    value: _decoration
                                });
                            }
                        } else if (codeInt <= 37) {
                            commands.push({
                                type: "setForegroundColor",
                                value: {
                                    type: "named",
                                    name: namedColors[codeInt - 30]
                                }
                            });
                        } else if (codeInt === 38) {
                            var _parseColor = parseColor(sequence, i),
                                _parseColor2 = _slicedToArray(_parseColor, 2),
                                offset = _parseColor2[0],
                                color = _parseColor2[1];
                            if (color) {
                                commands.push({
                                    type: "setForegroundColor",
                                    value: color
                                });
                            }
                            i += offset;
                        } else if (codeInt === 39) {
                            commands.push({
                                type: "resetForegroundColor"
                            });
                        } else if (codeInt <= 47) {
                            commands.push({
                                type: "setBackgroundColor",
                                value: {
                                    type: "named",
                                    name: namedColors[codeInt - 40]
                                }
                            });
                        } else if (codeInt === 48) {
                            var _parseColor3 = parseColor(sequence, i),
                                _parseColor4 = _slicedToArray(_parseColor3, 2),
                                _offset = _parseColor4[0],
                                _color = _parseColor4[1];
                            if (_color) {
                                commands.push({
                                    type: "setBackgroundColor",
                                    value: _color
                                });
                            }
                            i += _offset;
                        } else if (codeInt === 49) {
                            commands.push({
                                type: "resetBackgroundColor"
                            });
                        } else if (codeInt >= 90 && codeInt <= 97) {
                            commands.push({
                                type: "setForegroundColor",
                                value: {
                                    type: "named",
                                    name: namedColors[codeInt - 90 + 8]
                                }
                            });
                        } else if (codeInt >= 100 && codeInt <= 107) {
                            commands.push({
                                type: "setBackgroundColor",
                                value: {
                                    type: "named",
                                    name: namedColors[codeInt - 100 + 8]
                                }
                            });
                        }
                    }
                    return commands;
                }

                function createAnsiSequenceParser() {
                    var foreground = null;
                    var background = null;
                    var decorations2 = /* @__PURE__ */new Set();
                    return {
                        parse: function parse(value) {
                            var tokens = [];
                            var position = 0;
                            do {
                                var findResult = findSequence(value, position);
                                var _text = findResult.sequence ? value.substring(position, findResult.startPosition) : value.substring(position);
                                if (_text.length > 0) {
                                    tokens.push({
                                        value: _text,
                                        foreground: foreground,
                                        background: background,
                                        decorations: new Set(decorations2)
                                    });
                                }
                                if (findResult.sequence) {
                                    var commands = parseSequence(findResult.sequence);
                                    var _iterator23 = _createForOfIteratorHelper(commands),
                                        _step23;
                                    try {
                                        for (_iterator23.s(); !(_step23 = _iterator23.n()).done;) {
                                            var styleToken = _step23.value;
                                            if (styleToken.type === "resetAll") {
                                                foreground = null;
                                                background = null;
                                                decorations2.clear();
                                            } else if (styleToken.type === "resetForegroundColor") {
                                                foreground = null;
                                            } else if (styleToken.type === "resetBackgroundColor") {
                                                background = null;
                                            } else if (styleToken.type === "resetDecoration") {
                                                decorations2.delete(styleToken.value);
                                            }
                                        }
                                    } catch (err) {
                                        _iterator23.e(err);
                                    } finally {
                                        _iterator23.f();
                                    }
                                    var _iterator24 = _createForOfIteratorHelper(commands),
                                        _step24;
                                    try {
                                        for (_iterator24.s(); !(_step24 = _iterator24.n()).done;) {
                                            var _styleToken = _step24.value;
                                            if (_styleToken.type === "setForegroundColor") {
                                                foreground = _styleToken.value;
                                            } else if (_styleToken.type === "setBackgroundColor") {
                                                background = _styleToken.value;
                                            } else if (_styleToken.type === "setDecoration") {
                                                decorations2.add(_styleToken.value);
                                            }
                                        }
                                    } catch (err) {
                                        _iterator24.e(err);
                                    } finally {
                                        _iterator24.f();
                                    }
                                }
                                position = findResult.position;
                            } while (position < value.length);
                            return tokens;
                        }
                    };
                }

                // src/palette.ts
                var defaultNamedColorsMap = {
                    black: "#000000",
                    red: "#bb0000",
                    green: "#00bb00",
                    yellow: "#bbbb00",
                    blue: "#0000bb",
                    magenta: "#ff00ff",
                    cyan: "#00bbbb",
                    white: "#eeeeee",
                    brightBlack: "#555555",
                    brightRed: "#ff5555",
                    brightGreen: "#00ff00",
                    brightYellow: "#ffff55",
                    brightBlue: "#5555ff",
                    brightMagenta: "#ff55ff",
                    brightCyan: "#55ffff",
                    brightWhite: "#ffffff"
                };

                function createColorPalette() {
                    var namedColorsMap = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultNamedColorsMap;

                    function namedColor(name) {
                        return namedColorsMap[name];
                    }

                    function rgbColor(rgb) {
                        return "#".concat(rgb.map(function (x) {
                            return Math.max(0, Math.min(x, 255)).toString(16).padStart(2, "0");
                        }).join(""));
                    }

                    var colorTable;

                    function getColorTable() {
                        if (colorTable) {
                            return colorTable;
                        }
                        colorTable = [];
                        for (var i = 0; i < namedColors.length; i++) {
                            colorTable.push(namedColor(namedColors[i]));
                        }
                        var levels = [0, 95, 135, 175, 215, 255];
                        for (var r = 0; r < 6; r++) {
                            for (var g = 0; g < 6; g++) {
                                for (var b = 0; b < 6; b++) {
                                    colorTable.push(rgbColor([levels[r], levels[g], levels[b]]));
                                }
                            }
                        }
                        var level = 8;
                        for (var _i4 = 0; _i4 < 24; _i4++, level += 10) {
                            colorTable.push(rgbColor([level, level, level]));
                        }
                        return colorTable;
                    }

                    function tableColor(index) {
                        return getColorTable()[index];
                    }

                    function value(color) {
                        switch (color.type) {
                            case "named":
                                return namedColor(color.name);
                            case "rgb":
                                return rgbColor(color.rgb);
                            case "table":
                                return tableColor(color.index);
                        }
                    }

                    return {
                        value: value
                    };
                }

                function tokenizeAnsiWithTheme(theme, fileContents, options) {
                    var colorReplacements = resolveColorReplacements(theme, options);
                    var lines = splitLines(fileContents);
                    var colorPalette = createColorPalette(Object.fromEntries(namedColors.map(function (name) {
                        var _theme$colors;
                        return [name, (_theme$colors = theme.colors) === null || _theme$colors === void 0 ? void 0 : _theme$colors["terminal.ansi".concat(name[0].toUpperCase()).concat(name.substring(1))]];
                    })));
                    var parser = createAnsiSequenceParser();
                    return lines.map(function (line) {
                        return parser.parse(line[0]).map(function (token) {
                            var color;
                            var bgColor;
                            if (token.decorations.has("reverse")) {
                                color = token.background ? colorPalette.value(token.background) : theme.bg;
                                bgColor = token.foreground ? colorPalette.value(token.foreground) : theme.fg;
                            } else {
                                color = token.foreground ? colorPalette.value(token.foreground) : theme.fg;
                                bgColor = token.background ? colorPalette.value(token.background) : undefined;
                            }
                            color = applyColorReplacements(color, colorReplacements);
                            bgColor = applyColorReplacements(bgColor, colorReplacements);
                            if (token.decorations.has("dim")) color = dimColor(color);
                            var fontStyle = FontStyle.None;
                            if (token.decorations.has("bold")) fontStyle |= FontStyle.Bold;
                            if (token.decorations.has("italic")) fontStyle |= FontStyle.Italic;
                            if (token.decorations.has("underline")) fontStyle |= FontStyle.Underline;
                            return {
                                content: token.value,
                                offset: line[1],
                                // TODO: more accurate offset? might need to fork ansi-sequence-parser
                                color: color,
                                bgColor: bgColor,
                                fontStyle: fontStyle
                            };
                        });
                    });
                }

                function dimColor(color) {
                    var hexMatch = color.match(/#([0-9a-f]{3})([0-9a-f]{3})?([0-9a-f]{2})?/);
                    if (hexMatch) {
                        if (hexMatch[3]) {
                            var alpha = Math.round(Number.parseInt(hexMatch[3], 16) / 2).toString(16).padStart(2, "0");
                            return "#".concat(hexMatch[1]).concat(hexMatch[2]).concat(alpha);
                        } else if (hexMatch[2]) {
                            return "#".concat(hexMatch[1]).concat(hexMatch[2], "80");
                        } else {
                            return "#".concat(Array.from(hexMatch[1]).map(function (x) {
                                return "".concat(x).concat(x);
                            }).join(""), "80");
                        }
                    }
                    var cssVarMatch = color.match(/var\((--[\w-]+-ansi-[\w-]+)\)/);
                    if (cssVarMatch) return "var(".concat(cssVarMatch[1], "-dim)");
                    return color;
                }

                function _codeToTokensBase(internal, code) {
                    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
                    var _options$lang = options.lang,
                        lang = _options$lang === void 0 ? "text" : _options$lang,
                        _options$theme = options.theme,
                        themeName = _options$theme === void 0 ? internal.getLoadedThemes()[0] : _options$theme;
                    if (isPlainLang(lang) || isNoneTheme(themeName)) return splitLines(code).map(function (line) {
                        return [{
                            content: line[0],
                            offset: line[1]
                        }];
                    });
                    var _internal$setTheme = internal.setTheme(themeName),
                        theme = _internal$setTheme.theme,
                        colorMap = _internal$setTheme.colorMap;
                    if (lang === "ansi") return tokenizeAnsiWithTheme(theme, code, options);
                    var _grammar = internal.getLanguage(lang);
                    if (options.grammarState) {
                        if (options.grammarState.lang !== _grammar.name) {
                            throw new ShikiError$2("Grammar state language \"".concat(options.grammarState.lang, "\" does not match highlight language \"").concat(_grammar.name, "\""));
                        }
                        if (!options.grammarState.themes.includes(theme.name)) {
                            throw new ShikiError$2("Grammar state themes \"".concat(options.grammarState.themes, "\" do not contain highlight theme \"").concat(theme.name, "\""));
                        }
                    }
                    return tokenizeWithTheme(code, _grammar, theme, colorMap, options);
                }

                function _getLastGrammarState() {
                    for (var _len5 = arguments.length, args = new Array(_len5), _key7 = 0; _key7 < _len5; _key7++) {
                        args[_key7] = arguments[_key7];
                    }
                    if (args.length === 2) {
                        return getLastGrammarStateFromMap(args[1]);
                    }
                    var internal = args[0],
                        code = args[1],
                        _args$ = args[2],
                        options = _args$ === void 0 ? {} : _args$;
                    var _options$lang2 = options.lang,
                        lang = _options$lang2 === void 0 ? "text" : _options$lang2,
                        _options$theme2 = options.theme,
                        themeName = _options$theme2 === void 0 ? internal.getLoadedThemes()[0] : _options$theme2;
                    if (isPlainLang(lang) || isNoneTheme(themeName)) throw new ShikiError$2("Plain language does not have grammar state");
                    if (lang === "ansi") throw new ShikiError$2("ANSI language does not have grammar state");
                    var _internal$setTheme2 = internal.setTheme(themeName),
                        theme = _internal$setTheme2.theme,
                        colorMap = _internal$setTheme2.colorMap;
                    var _grammar = internal.getLanguage(lang);
                    return new GrammarState(_tokenizeWithTheme(code, _grammar, theme, colorMap, options).stateStack, _grammar.name, theme.name);
                }

                function tokenizeWithTheme(code, grammar, theme, colorMap, options) {
                    var result = _tokenizeWithTheme(code, grammar, theme, colorMap, options);
                    var grammarState = new GrammarState(_tokenizeWithTheme(code, grammar, theme, colorMap, options).stateStack, grammar.name, theme.name);
                    setLastGrammarStateToMap(result.tokens, grammarState);
                    return result.tokens;
                }

                function _tokenizeWithTheme(code, grammar, theme, colorMap, options) {
                    var _getGrammarStack;
                    var colorReplacements = resolveColorReplacements(theme, options);
                    var _options$tokenizeMaxL = options.tokenizeMaxLineLength,
                        tokenizeMaxLineLength = _options$tokenizeMaxL === void 0 ? 0 : _options$tokenizeMaxL,
                        _options$tokenizeTime = options.tokenizeTimeLimit,
                        tokenizeTimeLimit = _options$tokenizeTime === void 0 ? 500 : _options$tokenizeTime;
                    var lines = splitLines(code);
                    var stateStack = options.grammarState ? (_getGrammarStack = getGrammarStack(options.grammarState, theme.name)) !== null && _getGrammarStack !== void 0 ? _getGrammarStack : INITIAL : options.grammarContextCode != null ? _tokenizeWithTheme(options.grammarContextCode, grammar, theme, colorMap, _objectSpread(_objectSpread({}, options), {}, {
                        grammarState: undefined,
                        grammarContextCode: undefined
                    })).stateStack : INITIAL;
                    var actual = [];
                    var final = [];
                    for (var i = 0, len = lines.length; i < len; i++) {
                        var _lines$i = _slicedToArray(lines[i], 2),
                            line = _lines$i[0],
                            lineOffset = _lines$i[1];
                        if (line === "") {
                            actual = [];
                            final.push([]);
                            continue;
                        }
                        if (tokenizeMaxLineLength > 0 && line.length >= tokenizeMaxLineLength) {
                            actual = [];
                            final.push([{
                                content: line,
                                offset: lineOffset,
                                color: "",
                                fontStyle: 0
                            }]);
                            continue;
                        }
                        var resultWithScopes = void 0;
                        var tokensWithScopes = void 0;
                        var tokensWithScopesIndex = void 0;
                        if (options.includeExplanation) {
                            resultWithScopes = grammar.tokenizeLine(line, stateStack);
                            tokensWithScopes = resultWithScopes.tokens;
                            tokensWithScopesIndex = 0;
                        }
                        var result = grammar.tokenizeLine2(line, stateStack, tokenizeTimeLimit);
                        var tokensLength = result.tokens.length / 2;
                        for (var j = 0; j < tokensLength; j++) {
                            var startIndex = result.tokens[2 * j];
                            var nextStartIndex = j + 1 < tokensLength ? result.tokens[2 * j + 2] : line.length;
                            if (startIndex === nextStartIndex) continue;
                            var metadata = result.tokens[2 * j + 1];
                            var color = applyColorReplacements(colorMap[EncodedTokenMetadata.getForeground(metadata)], colorReplacements);
                            var fontStyle = EncodedTokenMetadata.getFontStyle(metadata);
                            var token = {
                                content: line.substring(startIndex, nextStartIndex),
                                offset: lineOffset + startIndex,
                                color: color,
                                fontStyle: fontStyle
                            };
                            if (options.includeExplanation) {
                                var themeSettingsSelectors = [];
                                if (options.includeExplanation !== "scopeName") {
                                    var _iterator25 = _createForOfIteratorHelper(theme.settings),
                                        _step25;
                                    try {
                                        for (_iterator25.s(); !(_step25 = _iterator25.n()).done;) {
                                            var setting = _step25.value;
                                            var selectors = void 0;
                                            switch (_typeof(setting.scope)) {
                                                case "string":
                                                    selectors = setting.scope.split(/,/).map(function (scope) {
                                                        return scope.trim();
                                                    });
                                                    break;
                                                case "object":
                                                    selectors = setting.scope;
                                                    break;
                                                default:
                                                    continue;
                                            }
                                            themeSettingsSelectors.push({
                                                settings: setting,
                                                selectors: selectors.map(function (selector) {
                                                    return selector.split(/ /);
                                                })
                                            });
                                        }
                                    } catch (err) {
                                        _iterator25.e(err);
                                    } finally {
                                        _iterator25.f();
                                    }
                                }
                                token.explanation = [];
                                var offset = 0;
                                while (startIndex + offset < nextStartIndex) {
                                    var tokenWithScopes = tokensWithScopes[tokensWithScopesIndex];
                                    var tokenWithScopesText = line.substring(tokenWithScopes.startIndex, tokenWithScopes.endIndex);
                                    offset += tokenWithScopesText.length;
                                    token.explanation.push({
                                        content: tokenWithScopesText,
                                        scopes: options.includeExplanation === "scopeName" ? explainThemeScopesNameOnly(tokenWithScopes.scopes) : explainThemeScopesFull(themeSettingsSelectors, tokenWithScopes.scopes)
                                    });
                                    tokensWithScopesIndex += 1;
                                }
                            }
                            actual.push(token);
                        }
                        final.push(actual);
                        actual = [];
                        stateStack = result.ruleStack;
                    }
                    return {
                        tokens: final,
                        stateStack: stateStack
                    };
                }

                function explainThemeScopesNameOnly(scopes) {
                    return scopes.map(function (scope) {
                        return {
                            scopeName: scope
                        };
                    });
                }

                function explainThemeScopesFull(themeSelectors, scopes) {
                    var result = [];
                    for (var i = 0, len = scopes.length; i < len; i++) {
                        var scope = scopes[i];
                        result[i] = {
                            scopeName: scope,
                            themeMatches: explainThemeScope(themeSelectors, scope, scopes.slice(0, i))
                        };
                    }
                    return result;
                }

                function matchesOne(selector, scope) {
                    return selector === scope || scope.substring(0, selector.length) === selector && scope[selector.length] === ".";
                }

                function matches(selectors, scope, parentScopes) {
                    if (!matchesOne(selectors[selectors.length - 1], scope)) return false;
                    var selectorParentIndex = selectors.length - 2;
                    var parentIndex = parentScopes.length - 1;
                    while (selectorParentIndex >= 0 && parentIndex >= 0) {
                        if (matchesOne(selectors[selectorParentIndex], parentScopes[parentIndex])) selectorParentIndex -= 1;
                        parentIndex -= 1;
                    }
                    if (selectorParentIndex === -1) return true;
                    return false;
                }

                function explainThemeScope(themeSettingsSelectors, scope, parentScopes) {
                    var result = [];
                    var _iterator26 = _createForOfIteratorHelper(themeSettingsSelectors),
                        _step26;
                    try {
                        for (_iterator26.s(); !(_step26 = _iterator26.n()).done;) {
                            var _step26$value = _step26.value,
                                selectors = _step26$value.selectors,
                                settings = _step26$value.settings;
                            var _iterator27 = _createForOfIteratorHelper(selectors),
                                _step27;
                            try {
                                for (_iterator27.s(); !(_step27 = _iterator27.n()).done;) {
                                    var selectorPieces = _step27.value;
                                    if (matches(selectorPieces, scope, parentScopes)) {
                                        result.push(settings);
                                        break;
                                    }
                                }
                            } catch (err) {
                                _iterator27.e(err);
                            } finally {
                                _iterator27.f();
                            }
                        }
                    } catch (err) {
                        _iterator26.e(err);
                    } finally {
                        _iterator26.f();
                    }
                    return result;
                }

                function _codeToTokensWithThemes(internal, code, options) {
                    var themes = Object.entries(options.themes).filter(function (i) {
                        return i[1];
                    }).map(function (i) {
                        return {
                            color: i[0],
                            theme: i[1]
                        };
                    });
                    var themedTokens = themes.map(function (t) {
                        var tokens2 = _codeToTokensBase(internal, code, _objectSpread(_objectSpread({}, options), {}, {
                            theme: t.theme
                        }));
                        var state = getLastGrammarStateFromMap(tokens2);
                        var theme = typeof t.theme === "string" ? t.theme : t.theme.name;
                        return {
                            tokens: tokens2,
                            state: state,
                            theme: theme
                        };
                    });
                    var tokens = syncThemesTokenization.apply(void 0, _toConsumableArray(themedTokens.map(function (i) {
                        return i.tokens;
                    })));
                    var mergedTokens = tokens[0].map(function (line, lineIdx) {
                        return line.map(function (_token, tokenIdx) {
                            var mergedToken = {
                                content: _token.content,
                                variants: {},
                                offset: _token.offset
                            };
                            if ("includeExplanation" in options && options.includeExplanation) {
                                mergedToken.explanation = _token.explanation;
                            }
                            tokens.forEach(function (t, themeIdx) {
                                var _t$lineIdx$tokenIdx = t[lineIdx][tokenIdx],
                                    _ = _t$lineIdx$tokenIdx.content,
                                    __ = _t$lineIdx$tokenIdx.explanation,
                                    ___ = _t$lineIdx$tokenIdx.offset,
                                    styles = _objectWithoutProperties(_t$lineIdx$tokenIdx, _excluded);
                                mergedToken.variants[themes[themeIdx].color] = styles;
                            });
                            return mergedToken;
                        });
                    });
                    var mergedGrammarState = themedTokens[0].state ? new GrammarState(Object.fromEntries(themedTokens.map(function (s) {
                        var _s$state;
                        return [s.theme, (_s$state = s.state) === null || _s$state === void 0 ? void 0 : _s$state.getInternalStack(s.theme)];
                    })), themedTokens[0].state.lang) : undefined;
                    if (mergedGrammarState) setLastGrammarStateToMap(mergedTokens, mergedGrammarState);
                    return mergedTokens;
                }

                function syncThemesTokenization() {
                    for (var _len6 = arguments.length, themes = new Array(_len6), _key8 = 0; _key8 < _len6; _key8++) {
                        themes[_key8] = arguments[_key8];
                    }
                    var outThemes = themes.map(function () {
                        return [];
                    });
                    var count = themes.length;
                    var _loop3 = function _loop3(i) {
                        var lines = themes.map(function (t) {
                            return t[i];
                        });
                        var outLines = outThemes.map(function () {
                            return [];
                        });
                        outThemes.forEach(function (t, i2) {
                            return t.push(outLines[i2]);
                        });
                        var indexes = lines.map(function () {
                            return 0;
                        });
                        var current = lines.map(function (l) {
                            return l[0];
                        });
                        while (current.every(function (t) {
                            return t;
                        })) {
                            var minLength = Math.min.apply(Math, _toConsumableArray(current.map(function (t) {
                                return t.content.length;
                            })));
                            for (var n = 0; n < count; n++) {
                                var token = current[n];
                                if (token.content.length === minLength) {
                                    outLines[n].push(token);
                                    indexes[n] += 1;
                                    current[n] = lines[n][indexes[n]];
                                } else {
                                    outLines[n].push(_objectSpread(_objectSpread({}, token), {}, {
                                        content: token.content.slice(0, minLength)
                                    }));
                                    current[n] = _objectSpread(_objectSpread({}, token), {}, {
                                        content: token.content.slice(minLength),
                                        offset: token.offset + minLength
                                    });
                                }
                            }
                        }
                    };
                    for (var i = 0; i < themes[0].length; i++) {
                        _loop3(i);
                    }
                    return outThemes;
                }

                function _codeToTokens(internal, code, options) {
                    var bg;
                    var fg;
                    var tokens;
                    var themeName;
                    var rootStyle;
                    var grammarState;
                    if ("themes" in options) {
                        var _options$defaultColor = options.defaultColor,
                            defaultColor = _options$defaultColor === void 0 ? "light" : _options$defaultColor,
                            _options$cssVariableP = options.cssVariablePrefix,
                            cssVariablePrefix = _options$cssVariableP === void 0 ? "--shiki-" : _options$cssVariableP;
                        var themes = Object.entries(options.themes).filter(function (i) {
                            return i[1];
                        }).map(function (i) {
                            return {
                                color: i[0],
                                theme: i[1]
                            };
                        }).sort(function (a, b) {
                            return a.color === defaultColor ? -1 : b.color === defaultColor ? 1 : 0;
                        });
                        if (themes.length === 0) throw new ShikiError$2("`themes` option must not be empty");
                        var themeTokens = _codeToTokensWithThemes(internal, code, options);
                        grammarState = getLastGrammarStateFromMap(themeTokens);
                        if (defaultColor && !themes.find(function (t) {
                            return t.color === defaultColor;
                        })) throw new ShikiError$2("`themes` option must contain the defaultColor key `".concat(defaultColor, "`"));
                        var themeRegs = themes.map(function (t) {
                            return internal.getTheme(t.theme);
                        });
                        var themesOrder = themes.map(function (t) {
                            return t.color;
                        });
                        tokens = themeTokens.map(function (line) {
                            return line.map(function (token) {
                                return mergeToken(token, themesOrder, cssVariablePrefix, defaultColor);
                            });
                        });
                        if (grammarState) setLastGrammarStateToMap(tokens, grammarState);
                        var themeColorReplacements = themes.map(function (t) {
                            return resolveColorReplacements(t.theme, options);
                        });
                        fg = themes.map(function (t, idx) {
                            return (idx === 0 && defaultColor ? "" : "".concat(cssVariablePrefix + t.color, ":")) + (applyColorReplacements(themeRegs[idx].fg, themeColorReplacements[idx]) || "inherit");
                        }).join(";");
                        bg = themes.map(function (t, idx) {
                            return (idx === 0 && defaultColor ? "" : "".concat(cssVariablePrefix + t.color, "-bg:")) + (applyColorReplacements(themeRegs[idx].bg, themeColorReplacements[idx]) || "inherit");
                        }).join(";");
                        themeName = "shiki-themes ".concat(themeRegs.map(function (t) {
                            return t.name;
                        }).join(" "));
                        rootStyle = defaultColor ? undefined : [fg, bg].join(";");
                    } else if ("theme" in options) {
                        var colorReplacements = resolveColorReplacements(options.theme, options);
                        tokens = _codeToTokensBase(internal, code, options);
                        var _theme = internal.getTheme(options.theme);
                        bg = applyColorReplacements(_theme.bg, colorReplacements);
                        fg = applyColorReplacements(_theme.fg, colorReplacements);
                        themeName = _theme.name;
                        grammarState = getLastGrammarStateFromMap(tokens);
                    } else {
                        throw new ShikiError$2("Invalid options, either `theme` or `themes` must be provided");
                    }
                    return {
                        tokens: tokens,
                        fg: fg,
                        bg: bg,
                        themeName: themeName,
                        rootStyle: rootStyle,
                        grammarState: grammarState
                    };
                }

                function mergeToken(merged, variantsOrder, cssVariablePrefix, defaultColor) {
                    var token = {
                        content: merged.content,
                        explanation: merged.explanation,
                        offset: merged.offset
                    };
                    var styles = variantsOrder.map(function (t) {
                        return getTokenStyleObject(merged.variants[t]);
                    });
                    var styleKeys = new Set(styles.flatMap(function (t) {
                        return Object.keys(t);
                    }));
                    var mergedStyles = {};
                    styles.forEach(function (cur, idx) {
                        var _iterator28 = _createForOfIteratorHelper(styleKeys),
                            _step28;
                        try {
                            for (_iterator28.s(); !(_step28 = _iterator28.n()).done;) {
                                var _key9 = _step28.value;
                                var value = cur[_key9] || "inherit";
                                if (idx === 0 && defaultColor) {
                                    mergedStyles[_key9] = value;
                                } else {
                                    var keyName = _key9 === "color" ? "" : _key9 === "background-color" ? "-bg" : "-".concat(_key9);
                                    var varKey = cssVariablePrefix + variantsOrder[idx] + (_key9 === "color" ? "" : keyName);
                                    mergedStyles[varKey] = value;
                                }
                            }
                        } catch (err) {
                            _iterator28.e(err);
                        } finally {
                            _iterator28.f();
                        }
                    });
                    token.htmlStyle = mergedStyles;
                    return token;
                }

                function _codeToHast(internal, code, options) {
                    var transformerContext = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
                        meta: {},
                        options: options,
                        codeToHast: function codeToHast(_code, _options) {
                            return _codeToHast(internal, _code, _options);
                        },
                        codeToTokens: function codeToTokens(_code, _options) {
                            return _codeToTokens(internal, _code, _options);
                        }
                    };
                    var input = code;
                    var _iterator29 = _createForOfIteratorHelper(getTransformers(options)),
                        _step29;
                    try {
                        for (_iterator29.s(); !(_step29 = _iterator29.n()).done;) {
                            var _transformer$preproce;
                            var transformer = _step29.value;
                            input = ((_transformer$preproce = transformer.preprocess) === null || _transformer$preproce === void 0 ? void 0 : _transformer$preproce.call(transformerContext, input, options)) || input;
                        }
                    } catch (err) {
                        _iterator29.e(err);
                    } finally {
                        _iterator29.f();
                    }
                    var _codeToTokens2 = _codeToTokens(internal, input, options),
                        tokens = _codeToTokens2.tokens,
                        fg = _codeToTokens2.fg,
                        bg = _codeToTokens2.bg,
                        themeName = _codeToTokens2.themeName,
                        rootStyle = _codeToTokens2.rootStyle,
                        grammarState = _codeToTokens2.grammarState;
                    var _options$mergeWhitesp = options.mergeWhitespaces,
                        mergeWhitespaces = _options$mergeWhitesp === void 0 ? true : _options$mergeWhitesp;
                    if (mergeWhitespaces === true) tokens = mergeWhitespaceTokens(tokens); else if (mergeWhitespaces === "never") tokens = splitWhitespaceTokens(tokens);
                    var contextSource = _objectSpread(_objectSpread({}, transformerContext), {}, {
                        get source() {
                            return input;
                        }
                    });
                    var _iterator30 = _createForOfIteratorHelper(getTransformers(options)),
                        _step30;
                    try {
                        for (_iterator30.s(); !(_step30 = _iterator30.n()).done;) {
                            var _transformer$tokens;
                            var _transformer = _step30.value;
                            tokens = ((_transformer$tokens = _transformer.tokens) === null || _transformer$tokens === void 0 ? void 0 : _transformer$tokens.call(contextSource, tokens)) || tokens;
                        }
                    } catch (err) {
                        _iterator30.e(err);
                    } finally {
                        _iterator30.f();
                    }
                    return tokensToHast(tokens, _objectSpread(_objectSpread({}, options), {}, {
                        fg: fg,
                        bg: bg,
                        themeName: themeName,
                        rootStyle: rootStyle
                    }), contextSource, grammarState);
                }

                function tokensToHast(tokens, options, transformerContext) {
                    var grammarState = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : getLastGrammarStateFromMap(tokens);
                    var transformers = getTransformers(options);
                    var lines = [];
                    var root = {
                        type: "root",
                        children: []
                    };
                    var _options$structure = options.structure,
                        structure = _options$structure === void 0 ? "classic" : _options$structure,
                        _options$tabindex = options.tabindex,
                        tabindex = _options$tabindex === void 0 ? "0" : _options$tabindex;
                    var preNode = {
                        type: "element",
                        tagName: "pre",
                        properties: _objectSpread(_objectSpread({
                            class: "shiki ".concat(options.themeName || ""),
                            style: options.rootStyle || "background-color:".concat(options.bg, ";color:").concat(options.fg)
                        }, tabindex !== false && tabindex != null ? {
                            tabindex: tabindex.toString()
                        } : {}), Object.fromEntries(Array.from(Object.entries(options.meta || {})).filter(function (_ref9) {
                            var _ref10 = _slicedToArray(_ref9, 1),
                                key = _ref10[0];
                            return !key.startsWith("_");
                        }))),
                        children: []
                    };
                    var codeNode = {
                        type: "element",
                        tagName: "code",
                        properties: {},
                        children: lines
                    };
                    var lineNodes = [];
                    var context = _objectSpread(_objectSpread({}, transformerContext), {}, {
                        structure: structure,
                        addClassToHast: addClassToHast,
                        get source() {
                            return transformerContext.source;
                        },
                        get tokens() {
                            return tokens;
                        },
                        get options() {
                            return options;
                        },
                        get root() {
                            return root;
                        },
                        get pre() {
                            return preNode;
                        },
                        get code() {
                            return codeNode;
                        },
                        get lines() {
                            return lineNodes;
                        }
                    });
                    tokens.forEach(function (line, idx) {
                        if (idx) {
                            if (structure === "inline") root.children.push({
                                type: "element",
                                tagName: "br",
                                properties: {},
                                children: []
                            }); else if (structure === "classic") lines.push({
                                type: "text",
                                value: "\n"
                            });
                        }
                        var lineNode = {
                            type: "element",
                            tagName: "span",
                            properties: {
                                class: "line"
                            },
                            children: []
                        };
                        var col = 0;
                        var _iterator31 = _createForOfIteratorHelper(line),
                            _step31;
                        try {
                            for (_iterator31.s(); !(_step31 = _iterator31.n()).done;) {
                                var token = _step31.value;
                                var tokenNode = {
                                    type: "element",
                                    tagName: "span",
                                    properties: _objectSpread({}, token.htmlAttrs),
                                    children: [{
                                        type: "text",
                                        value: token.content
                                    }]
                                };
                                if (typeof token.htmlStyle === "string") warnDeprecated("`htmlStyle` as a string is deprecated. Use an object instead.");
                                var style = stringifyTokenStyle(token.htmlStyle || getTokenStyleObject(token));
                                if (style) tokenNode.properties.style = style;
                                var _iterator33 = _createForOfIteratorHelper(transformers),
                                    _step33;
                                try {
                                    for (_iterator33.s(); !(_step33 = _iterator33.n()).done;) {
                                        var _transformer2$span;
                                        var _transformer2 = _step33.value;
                                        tokenNode = (_transformer2 === null || _transformer2 === void 0 || (_transformer2$span = _transformer2.span) === null || _transformer2$span === void 0 ? void 0 : _transformer2$span.call(context, tokenNode, idx + 1, col, lineNode, token)) || tokenNode;
                                    }
                                } catch (err) {
                                    _iterator33.e(err);
                                } finally {
                                    _iterator33.f();
                                }
                                if (structure === "inline") root.children.push(tokenNode); else if (structure === "classic") lineNode.children.push(tokenNode);
                                col += token.content.length;
                            }
                        } catch (err) {
                            _iterator31.e(err);
                        } finally {
                            _iterator31.f();
                        }
                        if (structure === "classic") {
                            var _iterator32 = _createForOfIteratorHelper(transformers),
                                _step32;
                            try {
                                for (_iterator32.s(); !(_step32 = _iterator32.n()).done;) {
                                    var _transformer$line;
                                    var transformer = _step32.value;
                                    lineNode = (transformer === null || transformer === void 0 || (_transformer$line = transformer.line) === null || _transformer$line === void 0 ? void 0 : _transformer$line.call(context, lineNode, idx + 1)) || lineNode;
                                }
                            } catch (err) {
                                _iterator32.e(err);
                            } finally {
                                _iterator32.f();
                            }
                            lineNodes.push(lineNode);
                            lines.push(lineNode);
                        }
                    });
                    if (structure === "classic") {
                        var _iterator34 = _createForOfIteratorHelper(transformers),
                            _step34;
                        try {
                            for (_iterator34.s(); !(_step34 = _iterator34.n()).done;) {
                                var _transformer$code;
                                var transformer = _step34.value;
                                codeNode = (transformer === null || transformer === void 0 || (_transformer$code = transformer.code) === null || _transformer$code === void 0 ? void 0 : _transformer$code.call(context, codeNode)) || codeNode;
                            }
                        } catch (err) {
                            _iterator34.e(err);
                        } finally {
                            _iterator34.f();
                        }
                        preNode.children.push(codeNode);
                        var _iterator35 = _createForOfIteratorHelper(transformers),
                            _step35;
                        try {
                            for (_iterator35.s(); !(_step35 = _iterator35.n()).done;) {
                                var _transformer3$pre;
                                var _transformer3 = _step35.value;
                                preNode = (_transformer3 === null || _transformer3 === void 0 || (_transformer3$pre = _transformer3.pre) === null || _transformer3$pre === void 0 ? void 0 : _transformer3$pre.call(context, preNode)) || preNode;
                            }
                        } catch (err) {
                            _iterator35.e(err);
                        } finally {
                            _iterator35.f();
                        }
                        root.children.push(preNode);
                    }
                    var result = root;
                    var _iterator36 = _createForOfIteratorHelper(transformers),
                        _step36;
                    try {
                        for (_iterator36.s(); !(_step36 = _iterator36.n()).done;) {
                            var _transformer4$root;
                            var _transformer4 = _step36.value;
                            result = (_transformer4 === null || _transformer4 === void 0 || (_transformer4$root = _transformer4.root) === null || _transformer4$root === void 0 ? void 0 : _transformer4$root.call(context, result)) || result;
                        }
                    } catch (err) {
                        _iterator36.e(err);
                    } finally {
                        _iterator36.f();
                    }
                    if (grammarState) setLastGrammarStateToMap(result, grammarState);
                    return result;
                }

                function mergeWhitespaceTokens(tokens) {
                    return tokens.map(function (line) {
                        var newLine = [];
                        var carryOnContent = "";
                        var firstOffset = 0;
                        line.forEach(function (token, idx) {
                            var isUnderline = token.fontStyle && token.fontStyle & FontStyle.Underline;
                            var couldMerge = !isUnderline;
                            if (couldMerge && token.content.match(/^\s+$/) && line[idx + 1]) {
                                if (!firstOffset) firstOffset = token.offset;
                                carryOnContent += token.content;
                            } else {
                                if (carryOnContent) {
                                    if (couldMerge) {
                                        newLine.push(_objectSpread(_objectSpread({}, token), {}, {
                                            offset: firstOffset,
                                            content: carryOnContent + token.content
                                        }));
                                    } else {
                                        newLine.push({
                                            content: carryOnContent,
                                            offset: firstOffset
                                        }, token);
                                    }
                                    firstOffset = 0;
                                    carryOnContent = "";
                                } else {
                                    newLine.push(token);
                                }
                            }
                        });
                        return newLine;
                    });
                }

                function splitWhitespaceTokens(tokens) {
                    return tokens.map(function (line) {
                        return line.flatMap(function (token) {
                            if (token.content.match(/^\s+$/)) return token;
                            var match = token.content.match(/^(\s*)(.*?)(\s*)$/);
                            if (!match) return token;
                            var _match = _slicedToArray(match, 4),
                                leading = _match[1],
                                content = _match[2],
                                trailing = _match[3];
                            if (!leading && !trailing) return token;
                            var expanded = [_objectSpread(_objectSpread({}, token), {}, {
                                offset: token.offset + leading.length,
                                content: content
                            })];
                            if (leading) {
                                expanded.unshift({
                                    content: leading,
                                    offset: token.offset
                                });
                            }
                            if (trailing) {
                                expanded.push({
                                    content: trailing,
                                    offset: token.offset + leading.length + content.length
                                });
                            }
                            return expanded;
                        });
                    });
                }

                function _codeToHtml(internal, code, options) {
                    var context = {
                        meta: {},
                        options: options,
                        codeToHast: function codeToHast(_code, _options) {
                            return _codeToHast(internal, _code, _options);
                        },
                        codeToTokens: function codeToTokens(_code, _options) {
                            return _codeToTokens(internal, _code, _options);
                        }
                    };
                    var result = toHtml(_codeToHast(internal, code, options, context));
                    var _iterator37 = _createForOfIteratorHelper(getTransformers(options)),
                        _step37;
                    try {
                        for (_iterator37.s(); !(_step37 = _iterator37.n()).done;) {
                            var _transformer$postproc;
                            var transformer = _step37.value;
                            result = ((_transformer$postproc = transformer.postprocess) === null || _transformer$postproc === void 0 ? void 0 : _transformer$postproc.call(context, result, options)) || result;
                        }
                    } catch (err) {
                        _iterator37.e(err);
                    } finally {
                        _iterator37.f();
                    }
                    return result;
                }

                var VSCODE_FALLBACK_EDITOR_FG = {
                    light: "#333333",
                    dark: "#bbbbbb"
                };
                var VSCODE_FALLBACK_EDITOR_BG = {
                    light: "#fffffe",
                    dark: "#1e1e1e"
                };
                var RESOLVED_KEY = "__shiki_resolved";

                function normalizeTheme(rawTheme) {
                    if (rawTheme !== null && rawTheme !== void 0 && rawTheme[RESOLVED_KEY]) return rawTheme;
                    var theme = _objectSpread({}, rawTheme);
                    if (theme.tokenColors && !theme.settings) {
                        theme.settings = theme.tokenColors;
                        delete theme.tokenColors;
                    }
                    theme.type || (theme.type = "dark");
                    theme.colorReplacements = _objectSpread({}, theme.colorReplacements);
                    theme.settings || (theme.settings = []);
                    var bg = theme.bg,
                        fg = theme.fg;
                    if (!bg || !fg) {
                        var _globalSetting$settin, _globalSetting$settin2, _theme$colors2, _theme$colors3;
                        var globalSetting = theme.settings ? theme.settings.find(function (s) {
                            return !s.name && !s.scope;
                        }) : undefined;
                        if (globalSetting !== null && globalSetting !== void 0 && (_globalSetting$settin = globalSetting.settings) !== null && _globalSetting$settin !== void 0 && _globalSetting$settin.foreground) fg = globalSetting.settings.foreground;
                        if (globalSetting !== null && globalSetting !== void 0 && (_globalSetting$settin2 = globalSetting.settings) !== null && _globalSetting$settin2 !== void 0 && _globalSetting$settin2.background) bg = globalSetting.settings.background;
                        if (!fg && theme !== null && theme !== void 0 && (_theme$colors2 = theme.colors) !== null && _theme$colors2 !== void 0 && _theme$colors2["editor.foreground"]) fg = theme.colors["editor.foreground"];
                        if (!bg && theme !== null && theme !== void 0 && (_theme$colors3 = theme.colors) !== null && _theme$colors3 !== void 0 && _theme$colors3["editor.background"]) bg = theme.colors["editor.background"];
                        if (!fg) fg = theme.type === "light" ? VSCODE_FALLBACK_EDITOR_FG.light : VSCODE_FALLBACK_EDITOR_FG.dark;
                        if (!bg) bg = theme.type === "light" ? VSCODE_FALLBACK_EDITOR_BG.light : VSCODE_FALLBACK_EDITOR_BG.dark;
                        theme.fg = fg;
                        theme.bg = bg;
                    }
                    if (!(theme.settings[0] && theme.settings[0].settings && !theme.settings[0].scope)) {
                        theme.settings.unshift({
                            settings: {
                                foreground: theme.fg,
                                background: theme.bg
                            }
                        });
                    }
                    var replacementCount = 0;
                    var replacementMap = /* @__PURE__ */new Map();

                    function getReplacementColor(value) {
                        var _theme$colorReplaceme;
                        if (replacementMap.has(value)) return replacementMap.get(value);
                        replacementCount += 1;
                        var hex = "#".concat(replacementCount.toString(16).padStart(8, "0").toLowerCase());
                        if ((_theme$colorReplaceme = theme.colorReplacements) !== null && _theme$colorReplaceme !== void 0 && _theme$colorReplaceme["#".concat(hex)]) return getReplacementColor(value);
                        replacementMap.set(value, hex);
                        return hex;
                    }

                    theme.settings = theme.settings.map(function (setting) {
                        var _setting$settings, _setting$settings2;
                        var replaceFg = ((_setting$settings = setting.settings) === null || _setting$settings === void 0 ? void 0 : _setting$settings.foreground) && !setting.settings.foreground.startsWith("#");
                        var replaceBg = ((_setting$settings2 = setting.settings) === null || _setting$settings2 === void 0 ? void 0 : _setting$settings2.background) && !setting.settings.background.startsWith("#");
                        if (!replaceFg && !replaceBg) return setting;
                        var clone = _objectSpread(_objectSpread({}, setting), {}, {
                            settings: _objectSpread({}, setting.settings)
                        });
                        if (replaceFg) {
                            var replacement = getReplacementColor(setting.settings.foreground);
                            theme.colorReplacements[replacement] = setting.settings.foreground;
                            clone.settings.foreground = replacement;
                        }
                        if (replaceBg) {
                            var _replacement = getReplacementColor(setting.settings.background);
                            theme.colorReplacements[_replacement] = setting.settings.background;
                            clone.settings.background = _replacement;
                        }
                        return clone;
                    });
                    for (var _i5 = 0, _Object$keys2 = Object.keys(theme.colors || {}); _i5 < _Object$keys2.length; _i5++) {
                        var _key10 = _Object$keys2[_i5];
                        if (_key10 === "editor.foreground" || _key10 === "editor.background" || _key10.startsWith("terminal.ansi")) {
                            var _theme$colors$_key;
                            if (!((_theme$colors$_key = theme.colors[_key10]) !== null && _theme$colors$_key !== void 0 && _theme$colors$_key.startsWith("#"))) {
                                var replacement = getReplacementColor(theme.colors[_key10]);
                                theme.colorReplacements[replacement] = theme.colors[_key10];
                                theme.colors[_key10] = replacement;
                            }
                        }
                    }
                    Object.defineProperty(theme, RESOLVED_KEY, {
                        enumerable: false,
                        writable: false,
                        value: true
                    });
                    return theme;
                }

                function resolveLangs(_x6) {
                    return _resolveLangs.apply(this, arguments);
                }

                function _resolveLangs() {
                    _resolveLangs = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(langs) {
                        return _regeneratorRuntime().wrap(function _callee12$(_context12) {
                            while (1) switch (_context12.prev = _context12.next) {
                                case 0:
                                    _context12.t0 = Array;
                                    _context12.t1 = Set;
                                    _context12.next = 4;
                                    return Promise.all(langs.filter(function (l) {
                                        return !isSpecialLang(l);
                                    }).map(/*#__PURE__*/function () {
                                        var _ref22 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(lang) {
                                            return _regeneratorRuntime().wrap(function _callee11$(_context11) {
                                                while (1) switch (_context11.prev = _context11.next) {
                                                    case 0:
                                                        _context11.next = 2;
                                                        return normalizeGetter(lang).then(function (r) {
                                                            return Array.isArray(r) ? r : [r];
                                                        });
                                                    case 2:
                                                        return _context11.abrupt("return", _context11.sent);
                                                    case 3:
                                                    case "end":
                                                        return _context11.stop();
                                                }
                                            }, _callee11);
                                        }));
                                        return function (_x11) {
                                            return _ref22.apply(this, arguments);
                                        };
                                    }()));
                                case 4:
                                    _context12.t2 = _context12.sent.flat();
                                    _context12.t3 = new _context12.t1(_context12.t2);
                                    return _context12.abrupt("return", _context12.t0.from.call(_context12.t0, _context12.t3));
                                case 7:
                                case "end":
                                    return _context12.stop();
                            }
                        }, _callee12);
                    }));
                    return _resolveLangs.apply(this, arguments);
                }

                function resolveThemes(_x7) {
                    return _resolveThemes.apply(this, arguments);
                }

                function _resolveThemes() {
                    _resolveThemes = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee14(themes) {
                        var resolved;
                        return _regeneratorRuntime().wrap(function _callee14$(_context14) {
                            while (1) switch (_context14.prev = _context14.next) {
                                case 0:
                                    _context14.next = 2;
                                    return Promise.all(themes.map(/*#__PURE__*/function () {
                                        var _ref23 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13(theme) {
                                            return _regeneratorRuntime().wrap(function _callee13$(_context13) {
                                                while (1) switch (_context13.prev = _context13.next) {
                                                    case 0:
                                                        if (!isSpecialTheme(theme)) {
                                                            _context13.next = 4;
                                                            break;
                                                        }
                                                        _context13.t0 = null;
                                                        _context13.next = 9;
                                                        break;
                                                    case 4:
                                                        _context13.t1 = normalizeTheme;
                                                        _context13.next = 7;
                                                        return normalizeGetter(theme);
                                                    case 7:
                                                        _context13.t2 = _context13.sent;
                                                        _context13.t0 = (0, _context13.t1)(_context13.t2);
                                                    case 9:
                                                        return _context13.abrupt("return", _context13.t0);
                                                    case 10:
                                                    case "end":
                                                        return _context13.stop();
                                                }
                                            }, _callee13);
                                        }));
                                        return function (_x12) {
                                            return _ref23.apply(this, arguments);
                                        };
                                    }()));
                                case 2:
                                    resolved = _context14.sent;
                                    return _context14.abrupt("return", resolved.filter(function (i) {
                                        return !!i;
                                    }));
                                case 4:
                                case "end":
                                    return _context14.stop();
                            }
                        }, _callee14);
                    }));
                    return _resolveThemes.apply(this, arguments);
                }

                var Registry = /*#__PURE__*/function (_Registry$) {
                    function Registry(_resolver, _themes, _langs) {
                        var _this15;
                        var _alias = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
                        _classCallCheck(this, Registry);
                        _this15 = _callSuper(this, Registry, [_resolver]);
                        _defineProperty(_this15, "_resolvedThemes", /* @__PURE__ */new Map());
                        _defineProperty(_this15, "_resolvedGrammars", /* @__PURE__ */new Map());
                        _defineProperty(_this15, "_langMap", /* @__PURE__ */new Map());
                        _defineProperty(_this15, "_langGraph", /* @__PURE__ */new Map());
                        _defineProperty(_this15, "_textmateThemeCache", /* @__PURE__ */new WeakMap());
                        _defineProperty(_this15, "_loadedThemesCache", null);
                        _defineProperty(_this15, "_loadedLanguagesCache", null);
                        _this15._resolver = _resolver;
                        _this15._themes = _themes;
                        _this15._langs = _langs;
                        _this15._alias = _alias;
                        _this15._themes.map(function (t) {
                            return _this15.loadTheme(t);
                        });
                        _this15.loadLanguages(_this15._langs);
                        return _this15;
                    }

                    _inherits(Registry, _Registry$);
                    return _createClass(Registry, [{
                        key: "getTheme",
                        value: function getTheme(theme) {
                            if (typeof theme === "string") return this._resolvedThemes.get(theme); else return this.loadTheme(theme);
                        }
                    }, {
                        key: "loadTheme",
                        value: function loadTheme(theme) {
                            var _theme = normalizeTheme(theme);
                            if (_theme.name) {
                                this._resolvedThemes.set(_theme.name, _theme);
                                this._loadedThemesCache = null;
                            }
                            return _theme;
                        }
                    }, {
                        key: "getLoadedThemes",
                        value: function getLoadedThemes() {
                            if (!this._loadedThemesCache) this._loadedThemesCache = _toConsumableArray(this._resolvedThemes.keys());
                            return this._loadedThemesCache;
                        }
                        // Override and re-implement this method to cache the textmate themes as `TextMateTheme.createFromRawTheme`
                        // is expensive. Themes can switch often especially for dual-theme support.
                        //
                        // The parent class also accepts `colorMap` as the second parameter, but since we don't use that,
                        // we omit here so it's easier to cache the themes.
                    }, {
                        key: "setTheme",
                        value: function setTheme(theme) {
                            var textmateTheme = this._textmateThemeCache.get(theme);
                            if (!textmateTheme) {
                                textmateTheme = Theme.createFromRawTheme(theme);
                                this._textmateThemeCache.set(theme, textmateTheme);
                            }
                            this._syncRegistry.setTheme(textmateTheme);
                        }
                    }, {
                        key: "getGrammar",
                        value: function getGrammar(name) {
                            if (this._alias[name]) {
                                var resolved = /* @__PURE__ */new Set([name]);
                                while (this._alias[name]) {
                                    name = this._alias[name];
                                    if (resolved.has(name)) throw new ShikiError("Circular alias `".concat(Array.from(resolved).join(" -> "), " -> ").concat(name, "`"));
                                    resolved.add(name);
                                }
                            }
                            return this._resolvedGrammars.get(name);
                        }
                    }, {
                        key: "loadLanguage",
                        value: function loadLanguage(lang) {
                            var _this16 = this;
                            if (this.getGrammar(lang.name)) return;
                            var embeddedLazilyBy = new Set(_toConsumableArray(this._langMap.values()).filter(function (i) {
                                var _i$embeddedLangsLazy;
                                return (_i$embeddedLangsLazy = i.embeddedLangsLazy) === null || _i$embeddedLangsLazy === void 0 ? void 0 : _i$embeddedLangsLazy.includes(lang.name);
                            }));
                            this._resolver.addLanguage(lang);
                            var grammarConfig = {
                                balancedBracketSelectors: lang.balancedBracketSelectors || ["*"],
                                unbalancedBracketSelectors: lang.unbalancedBracketSelectors || []
                            };
                            this._syncRegistry._rawGrammars.set(lang.scopeName, lang);
                            var g = this.loadGrammarWithConfiguration(lang.scopeName, 1, grammarConfig);
                            g.name = lang.name;
                            this._resolvedGrammars.set(lang.name, g);
                            if (lang.aliases) {
                                lang.aliases.forEach(function (alias) {
                                    _this16._alias[alias] = lang.name;
                                });
                            }
                            this._loadedLanguagesCache = null;
                            if (embeddedLazilyBy.size) {
                                var _iterator38 = _createForOfIteratorHelper(embeddedLazilyBy),
                                    _step38;
                                try {
                                    for (_iterator38.s(); !(_step38 = _iterator38.n()).done;) {
                                        var _this$_syncRegistry, _this$_syncRegistry2;
                                        var e = _step38.value;
                                        this._resolvedGrammars.delete(e.name);
                                        this._loadedLanguagesCache = null;
                                        (_this$_syncRegistry = this._syncRegistry) === null || _this$_syncRegistry === void 0 || (_this$_syncRegistry = _this$_syncRegistry._injectionGrammars) === null || _this$_syncRegistry === void 0 || _this$_syncRegistry.delete(e.scopeName);
                                        (_this$_syncRegistry2 = this._syncRegistry) === null || _this$_syncRegistry2 === void 0 || (_this$_syncRegistry2 = _this$_syncRegistry2._grammars) === null || _this$_syncRegistry2 === void 0 || _this$_syncRegistry2.delete(e.scopeName);
                                        this.loadLanguage(this._langMap.get(e.name));
                                    }
                                } catch (err) {
                                    _iterator38.e(err);
                                } finally {
                                    _iterator38.f();
                                }
                            }
                        }
                    }, {
                        key: "dispose",
                        value: function dispose() {
                            _superPropGet(Registry, "dispose", this, 3)([]);
                            this._resolvedThemes.clear();
                            this._resolvedGrammars.clear();
                            this._langMap.clear();
                            this._langGraph.clear();
                            this._loadedThemesCache = null;
                        }
                    }, {
                        key: "loadLanguages",
                        value: function loadLanguages(langs) {
                            var _iterator39 = _createForOfIteratorHelper(langs),
                                _step39;
                            try {
                                for (_iterator39.s(); !(_step39 = _iterator39.n()).done;) {
                                    var _lang4 = _step39.value;
                                    this.resolveEmbeddedLanguages(_lang4);
                                }
                            } catch (err) {
                                _iterator39.e(err);
                            } finally {
                                _iterator39.f();
                            }
                            var langsGraphArray = Array.from(this._langGraph.entries());
                            var missingLangs = langsGraphArray.filter(function (_ref11) {
                                var _ref12 = _slicedToArray(_ref11, 2),
                                    _ = _ref12[0],
                                    lang = _ref12[1];
                                return !lang;
                            });
                            if (missingLangs.length) {
                                var dependents = langsGraphArray.filter(function (_ref13) {
                                    var _lang$embeddedLangs;
                                    var _ref14 = _slicedToArray(_ref13, 2),
                                        _ = _ref14[0],
                                        lang = _ref14[1];
                                    return lang && ((_lang$embeddedLangs = lang.embeddedLangs) === null || _lang$embeddedLangs === void 0 ? void 0 : _lang$embeddedLangs.some(function (l) {
                                        return missingLangs.map(function (_ref15) {
                                            var _ref16 = _slicedToArray(_ref15, 1),
                                                name = _ref16[0];
                                            return name;
                                        }).includes(l);
                                    }));
                                }).filter(function (lang) {
                                    return !missingLangs.includes(lang);
                                });
                                throw new ShikiError("Missing languages ".concat(missingLangs.map(function (_ref17) {
                                    var _ref18 = _slicedToArray(_ref17, 1),
                                        name = _ref18[0];
                                    return "`".concat(name, "`");
                                }).join(", "), ", required by ").concat(dependents.map(function (_ref19) {
                                    var _ref20 = _slicedToArray(_ref19, 1),
                                        name = _ref20[0];
                                    return "`".concat(name, "`");
                                }).join(", ")));
                            }
                            for (var _i6 = 0, _langsGraphArray = langsGraphArray; _i6 < _langsGraphArray.length; _i6++) {
                                var _langsGraphArray$_i = _slicedToArray(_langsGraphArray[_i6], 2),
                                    _ = _langsGraphArray$_i[0],
                                    lang = _langsGraphArray$_i[1];
                                this._resolver.addLanguage(lang);
                            }
                            for (var _i7 = 0, _langsGraphArray2 = langsGraphArray; _i7 < _langsGraphArray2.length; _i7++) {
                                var _langsGraphArray2$_i = _slicedToArray(_langsGraphArray2[_i7], 2),
                                    _4 = _langsGraphArray2$_i[0],
                                    _lang3 = _langsGraphArray2$_i[1];
                                this.loadLanguage(_lang3);
                            }
                        }
                    }, {
                        key: "getLoadedLanguages",
                        value: function getLoadedLanguages() {
                            if (!this._loadedLanguagesCache) {
                                this._loadedLanguagesCache = _toConsumableArray(/* @__PURE__ */new Set([].concat(_toConsumableArray(this._resolvedGrammars.keys()), _toConsumableArray(Object.keys(this._alias)))));
                            }
                            return this._loadedLanguagesCache;
                        }
                    }, {
                        key: "resolveEmbeddedLanguages",
                        value: function resolveEmbeddedLanguages(lang) {
                            this._langMap.set(lang.name, lang);
                            this._langGraph.set(lang.name, lang);
                            if (lang.embeddedLangs) {
                                var _iterator40 = _createForOfIteratorHelper(lang.embeddedLangs),
                                    _step40;
                                try {
                                    for (_iterator40.s(); !(_step40 = _iterator40.n()).done;) {
                                        var embeddedLang = _step40.value;
                                        this._langGraph.set(embeddedLang, this._langMap.get(embeddedLang));
                                    }
                                } catch (err) {
                                    _iterator40.e(err);
                                } finally {
                                    _iterator40.f();
                                }
                            }
                        }
                    }]);
                }(Registry$1);
                var Resolver = /*#__PURE__*/function () {
                    function Resolver(engine, langs) {
                        var _this17 = this;
                        _classCallCheck(this, Resolver);
                        _defineProperty(this, "_langs", /* @__PURE__ */new Map());
                        _defineProperty(this, "_scopeToLang", /* @__PURE__ */new Map());
                        _defineProperty(this, "_injections", /* @__PURE__ */new Map());
                        _defineProperty(this, "_onigLib", void 0);
                        this._onigLib = {
                            createOnigScanner: function createOnigScanner(patterns) {
                                return engine.createScanner(patterns);
                            },
                            createOnigString: function createOnigString(s) {
                                return engine.createString(s);
                            }
                        };
                        langs.forEach(function (i) {
                            return _this17.addLanguage(i);
                        });
                    }

                    return _createClass(Resolver, [{
                        key: "onigLib",
                        get: function get() {
                            return this._onigLib;
                        }
                    }, {
                        key: "getLangRegistration",
                        value: function getLangRegistration(langIdOrAlias) {
                            return this._langs.get(langIdOrAlias);
                        }
                    }, {
                        key: "loadGrammar",
                        value: function loadGrammar(scopeName) {
                            return this._scopeToLang.get(scopeName);
                        }
                    }, {
                        key: "addLanguage",
                        value: function addLanguage(l) {
                            var _this18 = this;
                            this._langs.set(l.name, l);
                            if (l.aliases) {
                                l.aliases.forEach(function (a) {
                                    _this18._langs.set(a, l);
                                });
                            }
                            this._scopeToLang.set(l.scopeName, l);
                            if (l.injectTo) {
                                l.injectTo.forEach(function (i) {
                                    if (!_this18._injections.get(i)) _this18._injections.set(i, []);
                                    _this18._injections.get(i).push(l.scopeName);
                                });
                            }
                        }
                    }, {
                        key: "getInjections",
                        value: function getInjections(scopeName) {
                            var scopeParts = scopeName.split(".");
                            var injections = [];
                            for (var i = 1; i <= scopeParts.length; i++) {
                                var subScopeName = scopeParts.slice(0, i).join(".");
                                injections = [].concat(_toConsumableArray(injections), _toConsumableArray(this._injections.get(subScopeName) || []));
                            }
                            return injections;
                        }
                    }]);
                }();
                var instancesCount = 0;

                function createShikiInternalSync(options) {
                    instancesCount += 1;
                    if (options.warnings !== false && instancesCount >= 10 && instancesCount % 10 === 0) console.warn("[Shiki] ".concat(instancesCount, " instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call `highlighter.dispose()` to release unused instances."));
                    var isDisposed = false;
                    if (!options.engine) throw new ShikiError("`engine` option is required for synchronous mode");
                    var langs = (options.langs || []).flat(1);
                    var themes = (options.themes || []).flat(1).map(normalizeTheme);
                    var resolver = new Resolver(options.engine, langs);
                    var _registry = new Registry(resolver, themes, langs, options.langAlias);
                    var _lastTheme;

                    function getLanguage(name) {
                        ensureNotDisposed();
                        var _lang = _registry.getGrammar(typeof name === "string" ? name : name.name);
                        if (!_lang) throw new ShikiError("Language `".concat(name, "` not found, you may need to load it first"));
                        return _lang;
                    }

                    function getTheme(name) {
                        if (name === "none") return {
                            bg: "",
                            fg: "",
                            name: "none",
                            settings: [],
                            type: "dark"
                        };
                        ensureNotDisposed();
                        var _theme = _registry.getTheme(name);
                        if (!_theme) throw new ShikiError("Theme `".concat(name, "` not found, you may need to load it first"));
                        return _theme;
                    }

                    function setTheme(name) {
                        ensureNotDisposed();
                        var theme = getTheme(name);
                        if (_lastTheme !== name) {
                            _registry.setTheme(theme);
                            _lastTheme = name;
                        }
                        var colorMap = _registry.getColorMap();
                        return {
                            theme: theme,
                            colorMap: colorMap
                        };
                    }

                    function getLoadedThemes() {
                        ensureNotDisposed();
                        return _registry.getLoadedThemes();
                    }

                    function getLoadedLanguages() {
                        ensureNotDisposed();
                        return _registry.getLoadedLanguages();
                    }

                    function loadLanguageSync() {
                        ensureNotDisposed();
                        for (var _len7 = arguments.length, langs2 = new Array(_len7), _key11 = 0; _key11 < _len7; _key11++) {
                            langs2[_key11] = arguments[_key11];
                        }
                        _registry.loadLanguages(langs2.flat(1));
                    }

                    function loadLanguage() {
                        return _loadLanguage.apply(this, arguments);
                    }

                    function _loadLanguage() {
                        _loadLanguage = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
                            var _len8,
                                langs2,
                                _key12,
                                _args4 = arguments;
                            return _regeneratorRuntime().wrap(function _callee4$(_context4) {
                                while (1) switch (_context4.prev = _context4.next) {
                                    case 0:
                                        for (_len8 = _args4.length, langs2 = new Array(_len8), _key12 = 0; _key12 < _len8; _key12++) {
                                            langs2[_key12] = _args4[_key12];
                                        }
                                        _context4.t0 = loadLanguageSync;
                                        _context4.next = 4;
                                        return resolveLangs(langs2);
                                    case 4:
                                        _context4.t1 = _context4.sent;
                                        return _context4.abrupt("return", (0, _context4.t0)(_context4.t1));
                                    case 6:
                                    case "end":
                                        return _context4.stop();
                                }
                            }, _callee4);
                        }));
                        return _loadLanguage.apply(this, arguments);
                    }

                    function loadThemeSync() {
                        ensureNotDisposed();
                        for (var _len9 = arguments.length, themes2 = new Array(_len9), _key13 = 0; _key13 < _len9; _key13++) {
                            themes2[_key13] = arguments[_key13];
                        }
                        var _iterator41 = _createForOfIteratorHelper(themes2.flat(1)),
                            _step41;
                        try {
                            for (_iterator41.s(); !(_step41 = _iterator41.n()).done;) {
                                var theme = _step41.value;
                                _registry.loadTheme(theme);
                            }
                        } catch (err) {
                            _iterator41.e(err);
                        } finally {
                            _iterator41.f();
                        }
                    }

                    function loadTheme() {
                        return _loadTheme.apply(this, arguments);
                    }

                    function _loadTheme() {
                        _loadTheme = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
                            var _len10,
                                themes2,
                                _key14,
                                _args5 = arguments;
                            return _regeneratorRuntime().wrap(function _callee5$(_context5) {
                                while (1) switch (_context5.prev = _context5.next) {
                                    case 0:
                                        ensureNotDisposed();
                                        for (_len10 = _args5.length, themes2 = new Array(_len10), _key14 = 0; _key14 < _len10; _key14++) {
                                            themes2[_key14] = _args5[_key14];
                                        }
                                        _context5.t0 = loadThemeSync;
                                        _context5.next = 5;
                                        return resolveThemes(themes2);
                                    case 5:
                                        _context5.t1 = _context5.sent;
                                        return _context5.abrupt("return", (0, _context5.t0)(_context5.t1));
                                    case 7:
                                    case "end":
                                        return _context5.stop();
                                }
                            }, _callee5);
                        }));
                        return _loadTheme.apply(this, arguments);
                    }

                    function ensureNotDisposed() {
                        if (isDisposed) throw new ShikiError("Shiki instance has been disposed");
                    }

                    function dispose() {
                        if (isDisposed) return;
                        isDisposed = true;
                        _registry.dispose();
                        instancesCount -= 1;
                    }

                    return _defineProperty({
                        setTheme: setTheme,
                        getTheme: getTheme,
                        getLanguage: getLanguage,
                        getLoadedThemes: getLoadedThemes,
                        getLoadedLanguages: getLoadedLanguages,
                        loadLanguage: loadLanguage,
                        loadLanguageSync: loadLanguageSync,
                        loadTheme: loadTheme,
                        loadThemeSync: loadThemeSync,
                        dispose: dispose
                    }, Symbol.dispose, dispose);
                }

                function createShikiInternal(_x8) {
                    return _createShikiInternal.apply(this, arguments);
                }

                function _createShikiInternal() {
                    _createShikiInternal = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee15(options) {
                        var _yield$Promise$all, _yield$Promise$all2, themes, langs, engine;
                        return _regeneratorRuntime().wrap(function _callee15$(_context15) {
                            while (1) switch (_context15.prev = _context15.next) {
                                case 0:
                                    if (options.loadWasm) {
                                        warnDeprecated("`loadWasm` option is deprecated. Use `engine: createOnigurumaEngine(loadWasm)` instead.");
                                    }
                                    if (!options.engine) {
                                        warnDeprecated("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");
                                    }
                                    _context15.next = 4;
                                    return Promise.all([resolveThemes(options.themes || []), resolveLangs(options.langs || []), options.engine || createOnigurumaEngine(options.loadWasm || getDefaultWasmLoader())]);
                                case 4:
                                    _yield$Promise$all = _context15.sent;
                                    _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 3);
                                    themes = _yield$Promise$all2[0];
                                    langs = _yield$Promise$all2[1];
                                    engine = _yield$Promise$all2[2];
                                    return _context15.abrupt("return", createShikiInternalSync(_objectSpread(_objectSpread({}, options), {}, {
                                        themes: themes,
                                        langs: langs,
                                        engine: engine
                                    })));
                                case 10:
                                case "end":
                                    return _context15.stop();
                            }
                        }, _callee15);
                    }));
                    return _createShikiInternal.apply(this, arguments);
                }

                function createHighlighterCore(_x9) {
                    return _createHighlighterCore.apply(this, arguments);
                }

                function _createHighlighterCore() {
                    _createHighlighterCore = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee16(options) {
                        var internal;
                        return _regeneratorRuntime().wrap(function _callee16$(_context16) {
                            while (1) switch (_context16.prev = _context16.next) {
                                case 0:
                                    _context16.next = 2;
                                    return createShikiInternal(options);
                                case 2:
                                    internal = _context16.sent;
                                    return _context16.abrupt("return", _objectSpread(_objectSpread({
                                        getLastGrammarState: function getLastGrammarState() {
                                            for (var _len11 = arguments.length, args = new Array(_len11), _key15 = 0; _key15 < _len11; _key15++) {
                                                args[_key15] = arguments[_key15];
                                            }
                                            return _getLastGrammarState.apply(void 0, [internal].concat(args));
                                        },
                                        codeToTokensBase: function codeToTokensBase(code, options2) {
                                            return _codeToTokensBase(internal, code, options2);
                                        },
                                        codeToTokensWithThemes: function codeToTokensWithThemes(code, options2) {
                                            return _codeToTokensWithThemes(internal, code, options2);
                                        },
                                        codeToTokens: function codeToTokens(code, options2) {
                                            return _codeToTokens(internal, code, options2);
                                        },
                                        codeToHast: function codeToHast(code, options2) {
                                            return _codeToHast(internal, code, options2);
                                        },
                                        codeToHtml: function codeToHtml(code, options2) {
                                            return _codeToHtml(internal, code, options2);
                                        }
                                    }, internal), {}, {
                                        getInternalContext: function getInternalContext() {
                                            return internal;
                                        }
                                    }));
                                case 4:
                                case "end":
                                    return _context16.stop();
                            }
                        }, _callee16);
                    }));
                    return _createHighlighterCore.apply(this, arguments);
                }

                var shiki = shallowRef();
                var isShikiLoading = ref(true);
                var shikiLoadError = ref(null);
                var SUPPORTED_LANGUAGES = {
                    sql: function sql() {
                        return __vitePreload(function () {
                            return module.import('./sql-legacy-DP-5hSSN.js');
                        }, false ? __VITE_PRELOAD__ : void 0);
                    },
                    json: function json() {
                        return __vitePreload(function () {
                            return module.import('./json-legacy-y4xS8zJ6.js');
                        }, false ? __VITE_PRELOAD__ : void 0);
                    },
                    python: function python() {
                        return __vitePreload(function () {
                            return module.import('./python-legacy-Ijsycptt.js');
                        }, false ? __VITE_PRELOAD__ : void 0);
                    },
                    javascript: function javascript() {
                        return __vitePreload(function () {
                            return module.import('./javascript-legacy-ljD9xxgD.js');
                        }, false ? __VITE_PRELOAD__ : void 0);
                    },
                    bash: function bash() {
                        return __vitePreload(function () {
                            return module.import('./bash-legacy-CqDmOYij.js');
                        }, false ? __VITE_PRELOAD__ : void 0);
                    },
                    java: function java() {
                        return __vitePreload(function () {
                            return module.import('./java-legacy-CNAPio2S.js');
                        }, false ? __VITE_PRELOAD__ : void 0);
                    }
                };

                function initializeShiki() {
                    return _initializeShiki.apply(this, arguments);
                }

                function _initializeShiki() {
                    _initializeShiki = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee17() {
                        var highlighter;
                        return _regeneratorRuntime().wrap(function _callee17$(_context17) {
                            while (1) switch (_context17.prev = _context17.next) {
                                case 0:
                                    _context17.prev = 0;
                                    isShikiLoading.value = true;
                                    _context17.next = 4;
                                    return createHighlighterCore({
                                        engine: createOnigurumaEngine(function () {
                                            return __vitePreload(function () {
                                                return module.import('./wasm-legacy-D8HHj7WJ.js');
                                            }, false ? __VITE_PRELOAD__ : void 0);
                                        }),
                                        themes: [__vitePreload(function () {
                                            return module.import('./github-light-legacy-Cubr9Sya.js');
                                        }, false ? __VITE_PRELOAD__ : void 0)],
                                        langs: Object.values(SUPPORTED_LANGUAGES).map(function (lang) {
                                            return lang();
                                        })
                                    });
                                case 4:
                                    highlighter = _context17.sent;
                                    shiki.value = highlighter;
                                    _context17.next = 12;
                                    break;
                                case 8:
                                    _context17.prev = 8;
                                    _context17.t0 = _context17["catch"](0);
                                    shikiLoadError.value = _context17.t0;
                                    console.error("Failed to initialize Shiki:", _context17.t0);
                                case 12:
                                    _context17.prev = 12;
                                    isShikiLoading.value = false;
                                    return _context17.finish(12);
                                case 15:
                                case "end":
                                    return _context17.stop();
                            }
                        }, _callee17, null, [[0, 8, 12, 15]]);
                    }));
                    return _initializeShiki.apply(this, arguments);
                }

                initializeShiki();
                var _hoisted_1 = ["innerHTML"];
                var _sfc_main = exports("_", /* @__PURE__ */defineComponent({
                    __name: "ShikiCode",
                    props: {
                        code: {},
                        lang: {},
                        theme: {
                            default: "github-light"
                        }
                    },
                    setup: function setup(__props) {
                        var props = __props;
                        var highlighted = shallowRef("");
                        watchEffect(function () {
                            try {
                                if (!shiki.value) {
                                    highlighted.value = escapeHtml(props.code);
                                    return;
                                }
                                highlighted.value = shiki.value.codeToHtml(props.code, {
                                    lang: props.lang,
                                    theme: props.theme,
                                    transformers: [{
                                        pre: function pre(node) {
                                            node.properties.style = "white-space: break-spaces;overflow-wrap: break-word;";
                                        }
                                    }]
                                });
                            } catch (error) {
                                console.error("Failed to highlight code:", error);
                                highlighted.value = escapeHtml(props.code);
                            }
                        });
                        return function (_ctx, _cache) {
                            return openBlock(), createElementBlock("div", {
                                class: "p-4",
                                innerHTML: unref(highlighted)
                            }, null, 8, _hoisted_1);
                        };
                    }
                }));

                function useCopy() {
                    var copied = ref(false);
                    var timeout = useTimeoutFn(function () {
                        return copied.value = false;
                    }, 1500);

                    function copy(_x10) {
                        return _copy.apply(this, arguments);
                    }

                    function _copy() {
                        _copy = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(textToCopy) {
                            var textArea;
                            return _regeneratorRuntime().wrap(function _callee6$(_context6) {
                                while (1) switch (_context6.prev = _context6.next) {
                                    case 0:
                                        if (navigator.clipboard && window.isSecureContext) {
                                            navigator.clipboard.writeText(textToCopy);
                                            copied.value = true;
                                            timeout.start();
                                        } else {
                                            textArea = document.createElement("textarea");
                                            textArea.value = textToCopy;
                                            textArea.style.position = "absolute";
                                            textArea.style.opacity = "0";
                                            textArea.style.left = "-999999px";
                                            textArea.style.top = "-999999px";
                                            document.body.appendChild(textArea);
                                            textArea.focus();
                                            textArea.select();
                                            document.execCommand("copy");
                                            textArea.remove();
                                            copied.value = true;
                                            timeout.start();
                                        }
                                    case 1:
                                    case "end":
                                        return _context6.stop();
                                }
                            }, _callee6);
                        }));
                        return _copy.apply(this, arguments);
                    }

                    return {
                        copied: copied,
                        copy: copy
                    };
                }
            }
        };
    });
})();
